C# – Tips and Tricks
‘Getter’ vs. ‘Auto-Property Initializer’
A normal ‘getter’, like;
/// <summary>
/// Gets the image.
/// </summary>
/// <value>The image.</value>
public override Image Image
{
get
{
return Common.Icons.Get("StraightElevator");
}
}
or the newer ‘Expression Bodied Property’ style
public override Image Image => Common.Icons.Get("StraightElevator");
will call
Common.Icons.Get("StraightElevator")
and return the image reference every time it is called.
But did we really intend this ?
In above example we know from our domain knowledge that the image resource should probably have been a const or readonly reference since the image is loaded from disk and never changed during runtime.
So why;
- Push a string argument to stack
- Make ‘Icons.Get() fetch the image resource from it’s storage
- Push the image reference to the stack
- over and over – just to get the same result again and again ?
A better solution would be to fetch the image once and store it in a readonly field.
But instead of doing the whole cermony of; declaring a readonly field, initializing it in the contructor and create a getter – you can simpy use the ‘Auto-Property Initializer’ (C#6.0 syntax feature), like so;
/// <summary>
/// Gets the image.
/// </summary>
/// <value>The image.</value>
public override Image Image { get; } = Common.Icons.Get("StraightElevator");
This creates a readonly field, initializes it once and gives you a public property all in one line of code. And used in the right scenarios it helps performance, while at the same time minimizes SLOC count – a win-win ?.