C
C#5mo ago
enrico11011

✅ how do you properly handle a "Possible null reference return"?

i've got a property on my class that looks like so
private ViewModelBase? _CurrentPage;
...
public ViewModelBase CurrentPage
{
get { return _CurrentPage; }
set { this.RaiseAndSetIfChanged(ref _CurrentPage, value); }
}
private ViewModelBase? _CurrentPage;
...
public ViewModelBase CurrentPage
{
get { return _CurrentPage; }
set { this.RaiseAndSetIfChanged(ref _CurrentPage, value); }
}
vs is giving me a green squiggly in the get {} block saying the value might be null. The program itself compiles and runs but just out of curiosity how do you properly resolve the warning?
10 Replies
jcotton42
jcotton425mo ago
_CurrentPage (which really should be spelled _currentPage fwiw) is declared as nullable, but CurrentPage isn't
enrico11011
enrico11011OP5mo ago
is underscore + lowercase starting letter the generally accepted convention for private backing fields?
jcotton42
jcotton425mo ago
underscore is personal preference, but yes, they should be camelCase, not PascalCase
enrico11011
enrico11011OP5mo ago
got it. both have to be nullable and prefer camelCase thanks
jcotton42
jcotton425mo ago
also, consider using something like the mvvm toolkit to handle much of the drudgery for you https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
Introduction to the MVVM Toolkit - Community Toolkits for .NET
An overview of how to get started with the MVVM Toolkit and to the APIs it contains
ero
ero5mo ago
do they? i would think neither should be nullable?
enrico11011
enrico11011OP5mo ago
now that I think about it yeah probably. idk this is my first time with avalonia and i've only been doing C# for, like, a month now
jcotton42
jcotton425mo ago
I would use the MVVM toolkit, it will save you a lot of boilerplate.
enrico11011
enrico11011OP5mo ago
so they say, but I've only just gotten the hang of MVVM with reactive i'll keep it in mind though, thanks doesn't help that a lot of the reading material on either framework does nothing to introduce you to the pattern

Did you find this page helpful?