I have a List<string> myList
in my class that I want to be readonly for the class users.
List<strign> myList {get;}
private void SetListValue()
{
myList = new List<string>();
myList.Add("ss");
}
Like this I thought I could set the myList
value inside my class in my private members and make it readonly for the class users. But I realised that declaring it that way I'm unable to set any value.
Try:
public List<string> myList {get; private set;}
This will let you set it inside your class, but not outside. Note that this will not stop external clients updating your list, only the reference to it.
A private setter for a List, Collection, etc. means that the entire list cannot be replaced by consumers, but it does nothing to protect the public members of the list.
For example:
public class MyClass
{
public IList<string> MyList {get; private set;}
public MyClass()
{
MyList = new List<string>(){"One","Two", "Three"};
}
}
public class Consumer
{
public void DoSomething()
{
MyClass myClass = new MyClass();
myClass.MyList = new List<string>(); // This would not be allowed,
// due to the private setter
myClass.MyList.Add("new string"); // This would be allowed, because it's
// calling a method on the existing
// list--not replacing the list itself
}
}
In order to prevent consumers from altering the members of the list you could expose it as a Read-only interface, such as IEnumerable<string>
, ReadOnlyCollection<string>
, or by calling List.AsReadOnly()
within the declaring class.
public class MyClass
{
public IList<string> MyList {get; private set;}
public MyClass()
{
MyList = new List<string>(){"One","Two", "Three"}.AsReadOnly();
}
}
public class Consumer
{
public void DoSomething()
{
MyClass myClass = new MyClass();
myClass.MyList = new List<string>(); // This would not be allowed,
// due to the private setter
myClass.MyList.Add("new string"); // This would not be allowed, the
// ReadOnlyCollection<string> would throw
// a NotSupportedException
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With