Monotomy
Monotomy

Reputation: 554

How to create a C# List with const content?

In C#: Is there a way to define the content of a List const/readonly like in C++?

C++ Example:

List<const Content> listWithConstContent;

Upvotes: 2

Views: 656

Answers (3)

SLaks
SLaks

Reputation: 887547

C# does not support immutability like that

Upvotes: 1

Karol
Karol

Reputation: 143

Read-only and immutable are different properties. Which one do you expect?

  • If you need readonlyness, there is no support for it from C# type system. You need to expose your object through interface that does not allow to mutate state of this object.
  • If you need immutability, you need to design your class to work that way. There is no way to make it magically immutable.

Upvotes: 1

David Arno
David Arno

Reputation: 43254

The List<T> class in the .NET framework is mutable. There is no equivalent of that C++ feature either in C#, or the CLR.

If you want an immutable list, then you need to use eg ImmutableList<T>

Upvotes: 1

Related Questions