C# needs to allow us to write code in a more functional, immutable style

Posted on Updated on

Since C# 6.0 is now feature-locked (and I can’t wait) it’s time to start talking about something that might be in the next version, assumedly called C# 7.0.

The big feature for me would be to get C# to help us write immutable code. That means they need to make it easy to write immutable classes (see my last post on Record types) and immutable local variables too.

I propose the following syntax:

var x = 0;  // 'x' is a regular mutable variable, and therefore
x = 5;      //  its value can be changed

let y = 0;  // This 'y' variable is immutable. In fact, it's not a 'variable'
            // any more. It is a 'value', and it cannot be changed.
y = 0;      // => Compiler error

The advantage of this is that ‘let’ is already a keyword in C# (it’s used in Linq expressions to do exactly this) meaning that there will be no inconsistency introduced by this change. ‘let’ bindings will assume you want to use type inference, just as with var. If you want (or need) to explicitly declare a value’s type you can add in the type name like so:

let int i = 0;

The ‘let’ / ‘var’ feature duality would match F#’s ‘let’ and ‘let mutable’ and Swift’s ‘let’ and ‘var’ concepts very well. C# needs to catch up!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s