CommunityToolkit / CommunityToolkit/dotnet

ObservableProperty should support lazy initialization.

Open
#136 3 comments 1 reaction 0 assignees View on GitHub
feature request :mailbox_with_mail:
Dominant language
C#
Stars
3.8k
Forks
400
PR merge metrics
No merged PRs in 30d

Description

### 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_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.