Thinking about delayed getters on properties in C#6.0 or after that

Here is a typical scenario where one postpones property value creation until the property getter is accessed:

private SomeType something;

public SomeType Something 
{
   get
   {
     if (something == null)
     {
       something = new SomeType();
     }
     return something;
   }
}

This pattern is usually applied when property SomeType is rarely used. It doesn’t make much difference on desktop applications (unless there is a ton of these properties) but it might make some performance gains on mobile apps where performance is more critical and memory is less abundant. Of course, one could use Lazy<T> but that would create an instance of Layz<T> instead plus the instance of SomeType eventually.

Now, there is a Expression bodies on property-like function members proposition for C# 6.0 that allows getter-only properties to be implemented with an expression, i.e.:

public string Name => First + " " + Last;

However, full lambdas aren’t supported thus something field can’t be assigned and we’d end up with a new SomeType instance each time.

So, I was thinking a bit about how that could be implemented and here is my proposition for delayed getter-only property assignment:

public SomeType Something => const new SomeType();

This would cause the instance of SomeType to be created only when getter is first time accessed and after that the same instance would be used just like in the original example.

What do you think?

Avtor: Anonymous, objavljeno na portalu SloDug.si (Arhiv)

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.