Properties with backing fields can easily be null. I often see properties which check the backing field to see if it is null. This is commonly done with an if statement with one line of initialization. One way to get around this is to use the coalescing operator in C#. If we use this in combination with an expressions, which might be a method, we are able to easily handle this property with one line.
Here is an example of what I am talking about.
private SomeType _someObject; public SomeType SomeObject { get { return _someObject ?? (_someObject = giveMeSomeObject()); } }
Notice how short and concise this is. I am able to with one line which is very clear handle this common scenario. Sure it doesn't always match this exactly, but I see plenty of properties people write where they do something similar.
I think that is very elegant and a lot nicer than doing this older style.
private SomeType _someObject; public SomeType SomeObject { get { if (_someObject == null) { _someObject = giveMeSomeObject(); } return _someObject; } }
Comments