Upcoming C# 7 Goodies

Tipalti
By Tipalti
Tipalti

Tipalti

Tipalti’s revolutionary approach to invoice-based AP automation and non-invoiced global partner payments is designed to free your finance and accounting team from doing complex, manual, unrewarding payables work.

Updated December 20, 2024

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:

  1. 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):

  1. (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:

  1. (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:

  1. 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:

  1. 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.

  1. switch(obj)
  2. {
  3.      casestringstr:
  4.      break;
  5.      caseintnum when num > 0:
  6.      break;
  7.      caseintnum:
  8.      break;
  9.      casenull:
  10.      break;
  11.      caseIEnumerable<int> list when !list.Any():
  12.      break;
  13.      caseIEnumerable<int> list:
  14.      break;
  15. }

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.

  1. if(value isinti)
  2. {
  3.      intnumber = 35 + i;
  4. }

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.

  1. publicintGiveRaise(intemployeeId, uintamount)
  2. {
  3.       Logger logger = newLogger();
  4.       Employee GetEmployee(intid)
  5.       {
  6.           // fetch the employee from the data store ...
  7.           logger.DebugLog(...);
  8.           returnemployee;
  9.       }
  10.       returnGetEmployee(employeeId)?.GiveRaise(amount);
  11. }

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:

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

Records (maybe)

Abbreviation of very simple declaration. For example:

  1. vclass Car (string Make, string Model, string Color);

will be translated to the following behind the scenes:

  1. classCar : IEquatable<Car>
  2. {
  3.      publicstringMake { get; }
  4.      publicstringModel { get; }
  5.      publicstringColor { get; }
  6.      /// will be generated with c’tor, copy c’tor, Equals etc. for free
  7. };

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.

  1. varp1 = newPoint { X = 1, Y = 2 };
  2. varp2 = 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.

Recommendations

You may also like