I currently know of two ways to make an instance immutable in C#:
Method 1 - Compile Time Immutability
void Foo()
{
// Will be serialized as metadata and inserted
// as a literal. Only valid for compile-time constants
const int bar = 100;
}
Method 2 - Readonly Fields
class Baz
{
private readonly string frob;
public Baz()
{
// Can be set once in the constructor
// Only valid on members, not local variables
frob = "frob";
}
}
It would be nice to have a guarantee that, some instance, once instantiated, will not be changed. const
and readonly
do this to a small degree, but are limited in their scope. I can only use const
for compile-time constants, and readonly
for member variables.
Is there any way to give a local variable immutability after its initial instantiation (the way readonly
works, but on a more general level)?
Scala does this with the var
keyword, which declares a new immutable value, which cannot be reassigned to after it gets its initial value:
var xs = List(1,2,3,4,5) // xs is a value - cannot be reassigned to
xs = List(1,2,3,4,5,6); // will not compile