Search code examples
c#.netinitializationautomatic-properties

How to initialize auto-property to not null in C#?


I have a property:

public Dictionary<string, string> MyProp { get; set; }

When I invoke that property to add an item, I get a NullReferenceException.

How would I do the null check in the property itself so it gives me a new one if it is null? While keeping in the auto-property pattern.


Solution

  • Without an explicit private variable the only other way would be to add some code to the constructor of the class:

    MyProp = new Dictionary<string,string>();
    

    As nza points out in their answer from C# 6.0 onwards you can do this:

    public Dictionary<string, string> MyProp { get; set; } = new Dictionary<string, string>();
    

    If you use this pattern then you'll get initialised properties whenever you add a new one, without having to add the initialisation in the class's constructor.