This is the third and the last post about new features in C# 7.0. Today I will focus on:
– local functions
– literal improvements
– ref returns
– few other minor improvements
Local functions
It means we can create local function in a method. I don’t think I will use it often. We can achieve similar effect with Func/Action delegates. Anyway it’s nice to have feature.
1 2 3 4 5 6 7 8 9 10 11 12 |
private double Count() { double result = 0; result += Math.Pow(2, 8); return AddMore(result).current; (double current, double previous) AddMore(double d) { return (d+100, d); } } |
Literal imporvements
We can write numbers with separator _ to improve readability or use binary literals to specify bit patterns instead of hexadecimal.
1 2 3 4 5 |
var a = 123_456_789; //int Console.WriteLine(a); // output: 123456789 var b = 0b1010_1010; Console.WriteLine(b); // output: 170 |
Ref returns
In C# 7.0 we can use ref to return reference to the specific thing, e.g. get reference to item number 1 from an array and store this reference in local variable. I think it can be helpful mostly for game developers for passing ref to big data structures.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public void Run() { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; ref int storageLocation = ref Find(array); Console.WriteLine(array[1] == 2); //true storageLocation = 11; Console.WriteLine(array[1] == 11); //true Console.WriteLine(array[1]); // 11 } public ref int Find(int[] tab) { return ref tab[1]; } |
Few other improvements
In C# 7.0 we get more improvements. I just want to list them shortly.
– Async methods can return other types than void, Task and Task<T>,
– we can use expression bodies in more places, e.g. accessors, constructors, finalizers. We can create constructor like this
1 |
public Person(string name) => names.TryAdd(id, name); |
– we can throw an exception in an expression
1 |
public Person(string name) => Name = name ?? throw new ArgumentNullException(nameof(name)); |
That’s all new features that we can use in C# 7.0. Hope you use it well 😉