
One thing I love about C# is that I'm constantly learning new ways to simplify and write less code. Perhaps PowerShell has a lot to do with this, but I put a lot of value in the power of the one-liner. With that, I wanted to share something small I recently discovered.
There are three main ways to initialize your read-only class properties: field initializer, constructor, or property accessor. The first thing you need to consider when determining the right approach is whether you should use a readonly or get-only variable. A readonly variable has two primary benefits: guaranteeing the value won't change and better ensuring thread-safety. I'm not going to go into either of these, but I will say, if you can make your variable readonly, do it. The main reason not to make your variable readonly is if its initialization is resource-heavy and the variable isn't always crucial. There are other things to consider, but I want to focus more on the implementation of this code rather than the reasoning behind deciding on a good approach.
Back in the .NET 2 days, I used the following approach to lazy loading.
private PersonCollection _people;
public PersonCollection People
{
get
{
if (this._people == null)
{
this._people = new PersonCollection();
}
return this._people;
}
}
One way to achieve a one-liner would be to use an inline if statement.
private PersonCollection _people;
public PersonCollection People
{
get { return ((this._people == null) ? (this._people = new PersonCollection()) : this._people); }
}
The main problem with this is there's more one-liner than simplicity. This is a common problem with the inline if statement. For this reason, I avoided this type of lazy load approach.
Recently, when hammering thru some code, typing == null just made me think about the ?? operator. For those that don't know, this is essentially a null-check included with .NET 2 to simplify the use of nullable types (Nullable<T>). If the value on the left is null, the value on the right is returned.
private PersonCollection _people;
public PersonCollection People
{
get { return this._people ?? (this._people = new PersonCollection()); }
}
Nothing revolutionary, but, as I mentioned before, I love my one-liners!