Initialization with the null coalescence operator?

Perhaps I do not have a good understanding ?? the operator has not yet encountered a design flaw that I could not explain.

Compare the following two properties, the only difference is how they are initialized: the first is explicitly initialized, and the second with the operator (or am I doing it wrong here?).

If I run data initialization with both properties, the collection based on the first property fills up as expected, and the second with ?? the operator is never populated and contains 0 elements in the collection.

Of course, there is something wrong with my assumption; what is the disadvantage here?

PS Please ignore the Install method , which should implement INotifyPropertyChanged in the base class and is not related to this problem (which is limited by the type of initialization).

// property version 1

private ObservableCollection<UserName> _userNameColl = new ObservableCollection<UserName>();
public ObservableCollection<UserName> UserNameColl
{
    get { return _userNameColl; }
    set { Set(ref _userNameColl, value); }
}

// property version 2

private ObservableCollection<UserName> _userNameColl;
public ObservableCollection<UserName> UserNameColl
{
    get { return _userNameColl ?? new ObservableCollection<UserName>(); }
    set { Set(ref _userNameColl, value); }
}

// simple class to create a collection of objects

public class UserName
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

// simple test populating the collection

for (int i = 0; i < 4; i++)
{
    // silly data init just for test

    UserNameColl.Add(new UserName()
    {
        Name = $"UserName No {i}",
        Age = 20 + i,
        Email = $"email{i}@local.lan"
    });
}
+4
source share
1 answer

The second never initializes your field, but always returns a new collection. Try instead:

public ObservableCollection<UserName> UserNameColl
{
    get { return _userNameColl ?? (_userNameColl = new ObservableCollection<UserName>()); }
    set { Set(ref _userNameColl, value); }
}
+4
source

Source: https://habr.com/ru/post/1666904/


All Articles