I created a property of type List in my class
public List<string> CategoryRef { get; set; }
Now when I wanna add a string to the list I try
Product p=new Product();
p.CategoryRef.Add("Nick");
The compiler yells at me saying the object isnt set to an instance of an object. How to I instantiate a property?
In the constructor you need to say
this.CategoryRef = new List<string>();
All that
public List<string> CategoryRef { get; set; }
does is declare an auto-property of type List<string>
named CategoryRef
. Implicitly behind this auto-property is a backing field, but that backing field receives the default value for objects of type List<string>
. Therefore, by default, the backing field is null
and this is why you must set it in the constructor (or somewhere else but before you use it for the first time).
Finally, you probably should not be exposing the setter publicly. At a minimum, it is better to say
public List<string> CategoryRef { get; private set; }
Do you really want clients of your class to be able to assign a new list to CategoryRef
? Probably not.
And in situations like this, I actually prefer a manual property so that I can make the backing field readonly.
private readonly List<string> categoryRef = new List<string>();
public List<string> CategoryRef {
get {
return this.categoryRef;
}
}
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