Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate A Property Of Type List<>

Tags:

c#

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?

like image 989
Nick LaMarca Avatar asked Mar 17 '11 20:03

Nick LaMarca


1 Answers

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;
    }
}
like image 175
jason Avatar answered Oct 30 '22 09:10

jason