Lazy instantiation one-liner of instance fields with the coalesce operator

It is hardly worth blogging, but...

Did you know that the return value of an assignment is the assignment? i.e.

class Person {
  public string Name;
}
...
Person p;
Console.WriteLine((p = new Person()).Name);

And did you know there is a coalesce operator since .NET 2.0 that will return the left-hand side if not null, or the right-hand side if the left-hand is null?

a ?? b;

If you combine these information snippets you get the modern one-liner for lazy instantiation of instance fields:

Person p;
public Person Example {
  get {
    return p ?? (p = new Person());
  }
}

Previous & Next

WPF + INotifyPropertyChanged Proxy = Epic Fail!A simple way to start your code in a different AppDomain

Comments