4 ms·
>Why can’t I make local variables immutable? How it'd work in such a case: You declare immutable variable "a" which's an instance of a class and then you exe
by tester756 4y ago
>Why can’t I make local variables immutable?
How it'd work in such a case:
You declare immutable variable "a" which's an instance of a class
and then you execute "DoSomething" method which mutates under the hood?
Compilation error? runtime error?
Anyway have you tried records?
- codeflo 4y agoI’d be fine with semantics similar to readonly fields (and incidentally, “const” in JavaScript): you can’t reassign the variable, but the contained object can do what it wants. To your last question: Yes, records are really nice syntactic sugar for classes that want to behave like values.
- awild 4y agoIt's usually on a syntactical level, to disable reassigning a value. For objects this means the reference is still mutable, value types are locked. Js has const, C has const, Java final. Imho it'd be awesome if mutability were not the default and we would have to mark mutability, but until then any variable that doesn't need it, is final. Which also helps skimming code
- tester756 4y ago>Js has const, C has const, Java final. C# has readonly and const >Imho it'd be awesome if mutability were not the default If they decided one day that - "let's make immutable by default", then it'd be performance hit - wouldn't it?
- awild 4y ago> If they decided one day that - "let's make immutable by default", then it'd be performance hit - wouldn't it? Not really. It's just a syntactic default, reassigning local variables should be discouraged from except for iterators etc. It just fosters bad habits. For example, A list can still be mutated like usual, the reference however may not change. This usually allows compilers to do optimizations in multithreaded situations. But that's not why I code that way, it reduces the cognitive burden of keeping track which variables are actual moving parts as opposed to context/names etc. > C# has readonly and const Haven't written C# in a few years, GP was talking about variables as far as I can tell and their lack of immutability.
- kroltan 4y agoC# does not (as far as I know) have readonly or const for local variables, only to fields. You can even have consts inside method bodies, but they are only actual compile-time constants. codeflo means to declare a local variable that cannot be reassigned later. void Foo() { // this is possible in C# today, but only for compile-time constants const int Bar = 42; // this is what codeflo wants: variables that cannot be changed after declaration, but can hold runtime values readonly string text = $"Blah: {Bar + System.Environment.ProcessorCount}"; // with such a variable, you wouldn't be able to reassign it later: text = "Some other text"; // the line above would be a compile-time error, just like trying to reassign to a readonly field. }