Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a readonly C# List by non declaring its set attribute

Tags:

c#

.net

list

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.

like image 701
anmarti Avatar asked Aug 26 '13 13:08

anmarti


2 Answers

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.

like image 115
Adrian Wragg Avatar answered Oct 04 '22 21:10

Adrian Wragg


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
    }
}
like image 38
STW Avatar answered Oct 04 '22 23:10

STW