简体   繁体   中英

Instantiate A Property Of Type List<>

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;
    }
}

In the constructor of the object, you should have a line that sets the property to a new list.

public class Product{
   public Product()
   {
      CategoryRef = new List<string>();
   }

   public List<string> CategoryRef{ get; set;}
}

I would perhaps try something like the below

public class Product{

   public List<string> CategoryRef{ get; set;} = new List<string>();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM