I use C# in production. It's a great language. It has implemented a lot of really powerful features like pattern matching and linq. If I was going to change one thing about C#, it would be to make variables immutable by default. Rust does this really well, and I'm considering Rust as one of my favorite languages because of this. Here's how I arrived at this being my favorite Rust feature and what I think it would look like for C# to implement something like this.
Everyone on my team would agree that important transformations should not be hidden by side effects. Likewise, that immutability is generally a good practice. However, any code base will start to age after a number of years, so you if the compiler allows you to do something, you can probably find an example of it.
I found one such example working through a bug:
// line 1 var tags = new List<tag>(); var editedLines = lines.Where(line => line.IsEdited); // ...line 200 var transformedEditedLines = TransformEditedLines(editedLines, parameter2, parameter3, tags); // ...line 400 Submit(transformedEditedLines, transformedNewLines, tags);
The bug said that the tags were being set wrong. It took me a long time to figure out where the tags were even being set. There was no method for it, yet by the time it got to Submit(), they were there.
As you can guess by the lines I've included, they were being set in TransformEditedLines(). You can understand my confusion because it looks like TransformEditedLines() is a pure function which takes in the parameters it needs and spits out the lines after they're transformed.
First, when you're writing the code, you would start to default to setting it in the place of initialization. That would decrease that chance that anyone would write this mutable mess out of convenience.
Secondly, when you're reading the code, you would know from the definition whether to look out for a mutable mess. There would be an assumption of side effects, so even functions that pure would raise a warning flag.
Here's roughly what this could look like in C#:
// line 1 // notice the "mut" mutable keyword. var mut tags = new List<tag>(); var editedLines = lines.Where(line => line.IsEdited); // ...line 200 // notice the "mut" keyword here too. var transformedEditedLines = TransformEditedLines(editedLines, parameter2, parameter3, mut tags); // ...line 400 Submit(transformedEditedLines, transformedNewLines, tags);
Adding "mut" would be a lot like adding "private" to a field or "ref" to a parameter.
What is your favorite Rust feature? What else could C# learn from Rust? Do you disagree? Is default immutability a bad thing?
Read about immutability in Rust: Rust docs