Upcoming C# 7 Goodies

Microsoft is in the process of designing and building the next generation of C# (i.e. C# 7), and things look promising. It will be interesting to see the effect of Xamarin joining Microsoft, together with the release of .Net Core, Roslyn vNext and the synergy between all of the components.

In the meantime, here are some of the goodies that will be introduced with C# 7.

Binary literals

A nice little improvement is the ability to state binary literals.

For example, the decimal 16 can be represented as “b00010000”. This can easily become difficult to read. Microsoft is coming to our help with the ability to add underscores inside the literal.

Following this example:


Decimal 16 = binary b00010000 = binary b00_01_00_00 = binary b0001_0000

Multiple return values

This is an issue that can be solved today using “out” or by returning an object with some filled properties. The “out” keyword option is not very usable (definitely not in async functions), and I don’t see a lot of production code making use of this keyword.

With C# 7, you will be able to use the following syntax in order to return multi values (using tuples behind the scenes):


(int, int) GetUnpaidSalary(ISalaryProvider provider);

But how will the caller be able to know the intent of the different values? C# 7 allows the following:


(int Employee, int Salary) GetUnpaidSalary(ISalaryProvider provider);

This syntax is possible by using intent tuples (explained below)

Intent tuples

A new value type tuple is about to be introduced in C#7. In order to create a tuple:


var container = (1, 15000);

As you probably have experienced, tuples are somewhat difficult to work with when it comes to its intent. You will finally be able to declare an intent on the tuple members:


var result = (employee: 1, salary: 15000);

Behind the scenes, the tuple is still using Item1, Item2 etc., C# 7 lets you optionally set a tuple intent, in order to make your code more readable and easier to maintain.

Switch case pattern matching

Inspired by other (functional) languages, another nice to have language improvement with C#7 is extending C# switch case capabilities, giving it a wide range of abilities besides the current ones.

Assume object obj is passed to a method as parameter.


switch (obj)
{
     case string str:
     break;
     case int num when num > 0:
     break;
     case int num:
     break;
     case null:
     break;
     case IEnumerable<int> list when !list.Any():
     break;
     case IEnumerable<int> list:
     break;
}
 

Notice that besides switching on the type of the object, you can handle sub cases of the same type using the “when” keyword. In the example above, I could handle the case when obj is an integer and more specifically could handle the case of obj is a positive integer. In the same way that I could handle obj being an IEnumerable of int, and more specifically and IEnumerable of int with at least one item.

Pattern matching

Imagine this: instead of doing a type check and then a cast – do a type check and a cast as one statement.


if(value is int i)
{
     int number = 35 + i;
}

Local functions

You will be able to nest functions for local use only. The local function will have access to local variables defined in their enclosing scope.

The example below demonstrates a local function.


public int GiveRaise(int employeeId, uint amount)
{
      Logger logger = new Logger();
      Employee GetEmployee(int id)
      {
          // fetch the employee from the data store ...
          logger.DebugLog(...);
          return employee;
      }
      return GetEmployee(employeeId)?.GiveRaise(amount);
}

Ref returns and locals (maybe)

This feature is not yet certain to be added to C# 7. It will be useful in cases where you have arrays of value types or where  performance and memory allocations are crucial.

When passing value types and value type arrays, you would in some cases like to be more efficient and prevent copying your entire array while passing it around. You can do that today by passing a ref argument to a method.

The new C#7 feature that might be included is the ability to return a ref value

For example:


var image = ref GetBitmapById(long id, uint height, uint width);

Records (maybe)

Abbreviation of very simple declaration. For example:


class Car (string Make, string Model, string Color); 

will be translated to the following behind the scenes:


class Car : IEquatable<Car>
{
     public string Make { get; }
     public string Model { get; }
     public string Color { get; }
     /// will be generated with c’tor, copy c’tor, Equals etc. for free
};

Mutating objects (maybe)

Creating immutable objects with object initializers and the ability to mutate immutable objects easier. This is a nice syntactic sugar to a pretty common operation.


var p1 = new Point { X = 1, Y = 2 };
var p2 = p1 with { Y = -p1.Y };

What’s next?

I recommend trying those new features out, and provide feedback to Microsoft (@MadsTorgersen is always happy to get some feedback from the community!)

In order to play around with the new features – you will need:

  1. VS 15 preview
  2. Enable experimental for  the project using conditional compilation symbols “__DEMO__” and “__DEMO_EXPERIMENTAL__” for some really experimental features. Remember that C# 7 features are not final, can be changed or removed.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s