C
C#4d ago

Declaring a struct as a constant

None of these methods work, how would I go about it?
No description
9 Replies
canton7
canton74d ago
* Structs can't be const * Readonly only works with fields, not local variablets
fæ
OP4d ago
Then, how would I go about making a struct impossible to reassign
canton7
canton74d ago
You can't, not for a local variable
fæ
OP4d ago
Do you happen to know why? Why the keyword const can only be applied to primitives
canton7
canton74d ago
The 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
fæ
OP4d ago
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
canton7
canton74d ago
Yeah, there's been some discussion of that, but nothing yet
Anton
Anton4d ago
const is a compile time constant you can put your locals in a readonly struct that's the closest you can get also, in parameters
FusedQyou
FusedQyou4d ago
Because 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
Want results from more Discord servers?
Add your server