Reputation: 469
I have a simple class which overrides a list getter with predefined values, but, when calling the add method on the base constructor, it doesn't add the new value.
This is my code showing the error:
using System.Collections.Generic;
using NUnit.Framework;
public class SimpleTest
{
[Test]
public void Test()
{
var child = new ChildClass();
Assert.AreEqual(4, child.myList.Count);
}
private abstract class MyBaseClass
{
public abstract List<string> myList { get; }
public MyBaseClass(string addThis)
{
myList.Add(addThis);
}
}
private class ChildClass : MyBaseClass
{
public override List<string> myList => new List<string> { "one", "two", "three" };
public ChildClass() : base("four")
{
myList.Add("dsada");
}
}
}
Why is this caused? By not having a setter the list can't be replaced by a different one but the Add method should still work for this case.
Upvotes: 2
Views: 151
Reputation: 37050
When you write public override List<string> myList => new List<string> { "one", "two", "three" };
this is just a short-cut for the following:
public override List<string> myList { get { return new List<string> { "one", "two", "three" }; }
So you´re allways returning a completely new list.
Use this instead:
public override List<string> myList { get; } = new List<string> { "one", "two", "three" };
which will just set the initial value once for your property.
Alternativly use a backing-field:
private readonly List<string> _myList = new List<string> { "one", "two", "three" };
public override List<string> myList => _myList;
Upvotes: 3
Reputation: 32627
public override List<string> myList => new List<string> { "one", "two", "three" };
You are always returning a new list when you call the getter. Either create a field that stores the list and return that one or use an auto-implemented property, which you fill in the constructor.
Upvotes: 7