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

13 May 2008 in software-development | dotnet |

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()); } }

kick it on


comments powered by Disqus