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

user259286 picture user259286 · Apr 10, 2011 · Viewed 7.8k times · Source

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.

Thanks!

Answer

ChrisF picture ChrisF · Apr 10, 2011

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>();