ObservableProperty should support lazy initialization.
Describe the problem
ObservableProperty right now doesnt provide a way to initialize property or lazy initialize the properties. So in case where we need that we have to manually do that in the constructor.
Example
Following is a property (along with backing field) with traditional mvvm way and I am including lazy initialization in it so that this object will never be null when app wants to use it.
private DropDownsVM _dropDowns;
public DropDownsVM DropDowns { get => _dropDowns ??= new DropDownsVM(); set => SetProperty(ref _dropDowns, value); }
Now when I wanna use ObservableProperty annotation from Microsoft.Toolkit.Mvvm.ComponentModel I do the following way and have to add initialization in constructor.
public AppViewModel()
{
DropDowns = new DropDownsVM();
}
[ObservableProperty]
private DropDownsVM dropDowns;
Describe the solution
Ideally there should be a way to indicate that property should autogenerate the lazy initialization or atleast normal initialization.
Maybe Something like this
[ObservableProperty(new(), true)]
private DropDownsVM dropDowns;
[ObservableProperty(new(123), true)]
private DropDownsVM dropDowns;
in the first example [ObservableProperty(new(), true)] takes 2 parameters, first one being the automatic constructor of the object using latest c# language so we dnt have to write new DropDownsVM() fully, the 2nd parameter is a boolean indicating whether LazyInitialization=true
2nd example is same as first, only in this case we are providing a different constructor for the object and that constructor takes a parameter int, which is in this case 123 this lets us do all kind of initializations of the property right within the annotation and will reduce code a lot I think.
This could also work for other kinds of nonNullable objects i.e : providing a default value for a boolean or string etc.
Alternatives
No response
Additional info
Package version : Microsoft.Toolkit.Mvvm (7.1.2)
Help us help you
No response
Hello, 'touseefbsb! Thanks for submitting a new feature request. I've automatically added a vote 👍 reaction to help get things started. Other community members can vote to help us prioritize this feature in the future!
Hi @touseefbsb, thanks for the feedback. I've transferred this issue to the .NET Community Toolkit where we can better assist you.
[ObservableProperty(new(), true)]
Is not valid C# syntax. Either way, this is not something we're planning on looking into right now, to avoid making the attributes too complicated and clunky to use. This scenario is something that could rather be supported in a more natural way in C# 12 though, like:
[ObservableProperty]
public DropDownsVM DropDowns
{
get => field ??= new();
partial set;
}