Lazy instantiation one-liner of instance fields with the coalesce operator
13.05.2008 - 12:00 (2 years, 3 months, 3 weeks ago)
Filed under programming, .NET, TrivadisContent
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());
}
}
Comments
private readonly object pLock = new object(); private Person p; public Person Example { get { if(null == p) { lock(pLock) { // important because while waiting for the lock, // another thread may have assigned p! if(null == p) { p = new Person(); } } return p; } }*) edited by flq for better display of code
private readonly object pLock = new object(); private Person p; public Person Example { get { if(null == p) { lock(pLock) { // important because while waiting for the lock, // another thread may have assigned p! return p ?? (p = new Person()); // or if you prefer replace return with p = } } return p; } }Or, for the utterly lazy amongst us:
public Person Example { get { if (p == null) lock (pLock) p = p ?? new Person(); return p; } }lock (pLock) { return p ?? (p == new Person()); }equalsSystem.Threading.Monitor.Enter(pLock); try { return p ?? (p == new Person()); } finally { System.Threading.Monitor.Exit(pLock); }Since the Exit is inside the finally it will get executed (though I think I might have read some bug reports on .Net 1.0/1.1) But I have not heard any problems with 2.0+