In this article I will discuss about the C# 7.0 features with simple examples. The article also include the comparisons with the previous version.
For Trying C# 7.0 you need to do the following
- Visual Studio 15 preview
- Set __DEMO__ and__DEMO_EXPERIMENTAL__ as Conditional compilation symbol in project settings.
C# 7.0 Features
- Tuple – I have discussed about the tuples in C# in my article here. One of the use of the tuple is to return the mutiple values from the methods.
Tuple Before C# 7.0private Tuple
GetUserIDAndPwd() { return new Tuple ("UserID", "password"); } private void AnotherMethod() { var keys = GetUserIDAndPwd(); var userID = keys.Item1; var pwd = keys.Item2; } In the above code I am returning a tuple class which signifies the UserCredential class.
In C# 7.0
In C# 7.0 instead of using the Tuple we can declare the tuple type while using with the function as shown in the code below.
private (string UserName, string PassWord) GetUserIDAndPwd() { return ("Vikram", "Test123") } private void AnotherMethod() { var l1 = GetUserIDAndPwd(); var userID = l1.UserName; var pwd = l1.Password; }
Tuple deconstruction
The above GetUserIDAndPwdCan be called as below also
private void AnotherMethod() { (var usr, var pwd) = GetUserIDAndPwd(); var userID = usr; var pwd = pwd; }
- Out Keyword –Till C# 7.0 – We have to declare the out variable before passing it as parameter to the function. More about the out and ref keywords you can read here.
out keyword till C# 7.0public void GetName(Student s) { string firstName, lastName; // have to "predeclare" s.GetName(out firstName, out lastName); WriteLine($"({firstName}, {lastName})"); }
In C# 7.0
No need to declare the out parameter. It can be declare at the place of calling the method. Please check the code belowpublic void GetName(Student s) { s.GetName(out string firstName, out string lastName); WriteLine($"({firstName}, {lastName})"); }
Since the compiler will know the type of the argument at the run time. We could have used var keyword for calling the GetName method.
- Local Functions – Though it is possible to declare the Func and Action methods till C# 6.0. But they lack the support for Generics, ref and out parameters and params for the parameters. In C# 7.0 we can declare the functions in local scope as shown in the code below
public string GetName(int Id) { string Bar() { Console.WriteLine(“inner function”); } return Bar(); }
Recursion and forward references would work for local functions but not for lambda. No memory allocation would be done if we use local functions. ref and out parameters are allowed. Params can be used for parameters and these local functions can be generic.
Conclusion:
In this article I have discussed about some of the new features of C# 7.0.
Leave a Reply