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.
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.
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.
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.
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>();
You can initialize it in your constructor:
public MyClass()
{
MyProp = new Dictionary<string, string>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With