9

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?

3 Answers 3

19

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; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

It can be simplified further with auto-property initializer.
3

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

Comments

1

I would perhaps try something like the below

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.