Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Prism, binding properties and C# 8

$
0
0

I just started a new Xamarin.Forms project with Prism to test out some C# 8 features, first and foremost what it's like to work with nullable reference types enabled. I've come at an issue that I'm not sure what the best way to resolve it is. When declaring binding properties in my ViewModel, I use the following code:

private string _userName;
public string UserName
{
    get { return _userName; }
    set { SetProperty(ref _userName, value); }
}

The problem is that VS will show a warning saying "Non-nullable field '_userName' is uninitialized. Consider declaring the field as nullable." I considered the following solutions, but I'm not sure what the best one is:

  • Declaring the field nullable. But that would negate the whole thing of woring with nullable reference types.
  • Using code tags to suppress the warning for only the fields and not the properties
  • Assigning some default value (string.Empty) to the field. This seems fine for a simple string, but complications arise when using other types. When I have a Command, for example, I would have to initialize the field with a default empty Command just to then initialize the actual property with the command I actually want in the VM constructor. I would get this:
private ICommand _someCommand = new Command();
public ICommand SomeCommand
{
    get { return _someCommand; }
    set { SetProperty(ref _someCommand, value); }
}

// In the ctor:

SomeCommand = new Command(SomeMethod);

So I'm no seeing an ideal solution here. Can anybody help?


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>