Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 991
user259286 Avatar asked Apr 10 '11 17:04

user259286


People also ask

How do you give a property a default value?

Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.

What is non nullable property?

Non-nullable property 'propertyname' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. After carefully observing this error message, it makes sense for those properties. In order to minimize the likelihood that, our code causes the runtime to throw System.

What is auto-implemented property?

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.


2 Answers

For other people falling over this old question, there is a new feature in C# 6.0.

In C# 6.0, you can also initialize that property to some constant value in the same statement, like this:

public Dictionary<string, string> MyProp { get; set; } = new Dictionary<string, string>();
like image 83
nza Avatar answered Oct 16 '22 05:10

nza


You can initialize it in your constructor:

public MyClass()
{
  MyProp = new Dictionary<string, string>();
}
like image 38
David Avatar answered Oct 16 '22 07:10

David