Lazy Instantiation

Today I learnt a lesson on Lazy Instantiation with C#.

The lesson came from a bad (and rookie) oversight that I had made with setting up properties on a class.

I had a class similar to the following
[CSHARP]
public class MyClass
{
public int ItemOne { get; set; }
public Dictionary<string, string> DictionaryOne = new Dictionary<string, string>();
}
[/CSHARP]

The issue arose whenever I wanted to use the “DictionaryOne” object. Because I had instantiated it like I had, it would get re-instantiated with every call. Not a happy place.

Enter Lazy Instantiation.

By changing the DictionaryOne definition to a property using anonymous getters & setters, and then instantiating the object in the class’ constructor, I end up with a much nicer implemenation.

The finished product would look like

[CSHARP]
public class MyClass
{
public MyClass()
{
DictionaryOne = new Dictionary();
}

public Dictionary DictionaryOne { get; set; }
}
[/CSHARP]

Subscribe

0 comments