简体   繁体   中英

How to add value in a public property of List<string> type in c#?

private List<string> _Baseline = new List<string>();

public List<string> Baseline 
{
    get { return _Baseline; }
    set { _Baseline = value; }
}

How can I set this property? It does not let me add using the add method; it throws an "object reference null" error.

It should work if you did what you wrote here. I guess you are using generics, and I can't see them in your post.

If you have a complex expression, split it. For example, change ObjectA.Prop.Other.Xyz.Add(..) to:

SomeClass a = ObjectA.Prop;
SomeClass2 b = a.Other;
SomeClass3 c = b.Xyz;
c.Add(...)

this way you will find quickly where the null reference is.

Do you initialize the class (using new ) that holds this property before use?

There are two possible cases (assuming your code is in MyClass class):

//External code:
MyClass x = new MyClass();
x.Baseline = null; // Somewhere it'll be set to null.
x.Baseline.Add("Something"); // NullReferenceException

Or:

//External code:
MyClass x = null; // Somewhere the class itself is set to null.
x.Baseline.Add("Something"); // NullReferenceException

There are 3 possibilities:

  1. your list<string> is null
  2. the object containing your list<string> is null
  3. the item you are inserting is null

1 is addressed when you assign a new List to it

2 and 3 we can not ascertain from the code you post here.

if you do not intend to allow assignment of a new list object outside of your class, then you do not, as noted elsewhere, need a setter. You can either remove it or declare it private or protected, like this....

public List<string> Baseline 
{
    get { return _Baseline; }
    protected set { _Baseline = value; }
}

i got the same error since the declaration was not proper:

private List<string> _Baseline;    - incorrect
private List<string> _Baseline = new List<string>();    - correct

You might need to use IList:

private IList<string> _Baseline = new List<string>();

public IList<string> Baseline 
{
    get { return _Baseline; }
    set { _Baseline = value; }
}

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