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?
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.
ReadOnly collections prevents the modification of the collection which is defined with type ReadOnly.
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.
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.
You can expose a List<T>
as a ReadOnlyCollection<T>
by using the AsReadOnly()
method
class Foo { private List<int> myList; public ReadOnlyCollection<int> ReadOnlyList => myList.AsReadOnly(); }
class Foo { private List<int> myList; public ReadOnlyCollection<int> ReadOnlyList { get { return myList.AsReadOnly(); } } }
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