9 Replies
* Structs can't be const
* Readonly only works with fields, not local variablets
Then, how would I go about making a struct impossible to reassign
You can't, not for a local variable
Do you happen to know why?
Why the keyword
const
can only be applied to primitivesThe value of a const is baked into the assembly as a literal, and the compiler can't do that for arbitrary types that it doesn't know about
I see. I come from JS and therefore must've misunderstood the meaning of Const.
I wish C# had an equivalent for that feature, it's quite nice
Yeah, there's been some discussion of that, but nothing yet
const is a compile time constant
you can put your locals in a readonly struct
that's the closest you can get
also,
in
parametersBecause it must exist at compile time
And stuff like classes are created later
This is why you use
readonly
but your code does this in a method scope which isn't possible
So if you want an immutable local variable, then just don't reassign it in the method 😄
Remember structs are passed by value so even other methods won't mutate it