Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-Only List in C#

Tags:

c#

.net

list

I have some class with List-property:

class Foo {   private List<int> myList; } 

I want provide access to this field only for read.

I.e. I want property with access to Enumerable, Count, etc. and without access to Clear, Add, Remove, etc. How I can do it?

like image 518
AndreyAkinshin Avatar asked Jan 13 '11 12:01

AndreyAkinshin


People also ask

What is ReadOnly lists C#?

13 September 2013. In C# there is the readonly keyword that enforced the rule that the variable must be initialised as it's declared or in the constructor. This works as expected for simple types, but for objects and lists it's not quite like that. With a list, you can still add, remove and change items in the list.

What is ReadOnly collection?

ReadOnly collections prevents the modification of the collection which is defined with type ReadOnly.

Is a ReadOnly collection mutable?

The fact that ReadOnlyCollection is immutable means that the collection cannot be modified, i.e. no objects can be added or removed from the collection.

Are read only lists which Cannot be modified?

A read-only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using the get method or by using the Iterator of List, This kind of List is good for a certain requirement where parameters are final and can not be changed.


1 Answers

You can expose a List<T> as a ReadOnlyCollection<T> by using the AsReadOnly() method

C# 6.0 and later (using Expression Bodied Properties)

class Foo {     private List<int> myList;    public ReadOnlyCollection<int> ReadOnlyList => myList.AsReadOnly();  } 

C# 5.0 and earlier

class Foo {    private List<int> myList;    public ReadOnlyCollection<int> ReadOnlyList {      get {          return myList.AsReadOnly();      }   } } 
like image 176
FearlessHyena Avatar answered Oct 02 '22 11:10

FearlessHyena