Skip to content
Search the Knowledge Base
< All Topics

C# Tip: 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 ImageSource Image { get; } = Common.EmbeddedImageLoader.Get("PalletStand");

will call:

Common.EmbeddedImageLoader.Get("PalletStand");

and return the image reference every time it is called.

But did we really intend this ?

In the 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 ?

Next Logging and Diagnostic messages