Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readonly keyword does not make a List<> ReadOnly?

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

like image 265
Richard Avatar asked Apr 08 '12 21:04

Richard


People also ask

Can you add items to a readonly list C#?

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 the readonly keyword used for?

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.

Which keyword is used to create a read only variable in C?

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.

What is the purpose of readonly modifier in C#?

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.


1 Answers

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:

  • Is there a read-only generic dictionary available in .NET?
like image 198
Mark Byers Avatar answered Sep 22 '22 08:09

Mark Byers