anmarti
anmarti

Reputation: 5143

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

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.

Upvotes: 5

Views: 419

Answers (3)

STW
STW

Reputation: 46366

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

Upvotes: 5

Adrian Wragg
Adrian Wragg

Reputation: 7401

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.

Upvotes: 11

Sam Leach
Sam Leach

Reputation: 12956

You want a public property with a private setter. As below.

public List<string> myList { get; private set; }

Upvotes: 0

Related Questions