I have the following code in a public static class:
public static class MyList { public static readonly SortedList<int, List<myObj>> CharList; // ...etc. }
.. but even using readonly
I can still add items to the list from another class:
MyList.CharList[100] = new List<myObj>() { new myObj(30, 30) };
or
MyList.CharList.Add(new List<myObj>() { new myObj(30, 30) });
Is there a way to make the thing read only without changing the implementation of CharList (it'll break some stuff)? If I do have to change the implementation (to make it non-changeable), what would be the best way? I need it to be List<T, T>, so ReadOnlyCollection won't do
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.
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
The readonly keyword can be used to define a variable or an object as readable only. This means that the variable or object can be assigned a value at the class scope or in a constructor only. You cannot change the value or reassign a value to a readonly variable or object in any other method except the constructor.
Readonly Fields: In C#, you are allowed to declare a field using readonly modifier. It indicates that the assignment to the fields is only the part of the declaration or in a constructor to the same class.
The modifier readonly
means that the value cannot be assigned except in the declaration or constructor. It does not mean that the assigned object becomes immutable.
If you want your object to be immutable, you must use a type that is immutable. The type ReadOnlyCollection<T>
that you mentioned is an example of a immutable collection. See this related question for how to achieve the same for dictionaries:
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