C# 7 Features and High level overview. Tuples, Pattern matching, Literal improvements, Ref return types etc…

C# 7 Features: C# 7.0 has numbers of new features and these are foc0us on data consumption, code simplification, and performance improvement. In C# 7.0 biggest features are tuples (which makes it easy to have multiple results), and pattern matching( which simplifies code that is conditional on the shape of data). But there are many other small and big changes are also there, these features make our code more efficient and clear, and makes us more happy and productive.  Let’s see these features one by one.

C-sharp-7-features-technicalDiary

 

Out variables as C# 7 features:

Up to C# 6.0, using out parameters isn’t as fluid as we’d like. Up to C# 6.0, if we want to call a method with ‘out’ parameters we first have to declare variables to pass to it. Since we aren’t initializing these variables (they are going to be overwritten by the method after all), we also cannot use var to declare them, but need to specify the full type, see below snippet:

public void PrintStudentInfo(Student S)
{
    int rollNo, rollCode; // 1st we have to "declare"
    S.GetStudent(out rollNo, out rollCode);
    WriteLine($"({rollNo}, {rollCode})");
}

In C# 7.0 we are adding out variables; the ability to declare a variable at the point where it is passed as an out argument, see below snippet:

public void PrintStudentInfo(Student S)
{
    S.GetStudent(out rollNo, out rollCode);
    WriteLine($"({rollNo}, {rollCode})");
}

What is the Difference Between String and StringBuilder in C#.

Multiple return types in C# 7.0

Return multiple values from a method is now a common practice, options available up to C# 6.0 are less optimal as:

  • Anonymous types returned through a return type: High-performance overhead and no static type checking.
  • Custom-built transport type for every method: A lot of code overhead for a type whose purpose is just to temporarily group a few values.
  • Out parameters: Use is clunky (even with the improvements described above), and they don’t work with async methods.
  • return types: Verbose to use and require an allocation of a tuple object.

but to do better C# 7.0 brings tuple types and tuple literals for you. It just returns multiple values/types in form of tuple object. see below snippet

( string, string, string) getStudentInfo()
{
    //read data from database and set to respective veriable 
    string strName = "abc";
    string strDepartment = "CSE";
    string strCollege= "College";
        return (strName, strDepartment, strCollege); // return tuple literal
}

The method now effectively returns three strings, wrapped up as elements in a tuple value. The caller of the method will now receive a tuple, and can access the elements individually by following expression:

var student = GetStudentInfo();
WriteLine($"Student info as {student.Item1} {student.Item2} {student.Item3}.");

In above example, we can easily retrieve multiple values from tuples, but Item1, Item2 name are bit irrelevant so let’s assign some meaningful names before return, see below sample

(string strName, string strDepartment, string strCollege) getStudentInfo()
{
    //Retive data from database and set it to variables 
}

//Now when you call method get values with specific name as below 
var studentInfo= getEmpInfo();
WriteLine("student info as {studentInfo.strName} {studentInfo.strDepartment} {studentInfo.strCollege}.");

Additionally, you can return their name directly in tuple literal as below:

return (Name: strName, Department: strDepartment, College: strCollege);

Tuples are useful thing where you can replace hash table or dictionary easily, even you can return multiple values for a single key. Additionally, you can use it instead of List where you store multiple values at single position.

.NET also has a Tuple type but it is a reference type and that leads to performance issues, but C# 7.0 bring a Tuple with value type which is faster in performance and a mutable type.

Deconstruction:

Most of the time we don’t want to access whole tuple bundle or we just need internal values then we can use Deconstruction features of C# 7.0, we can easily deconstruct a tuple and fetch values that we need, following snippet will clear your doubt:

( string strName,  string strDepartment,  string strCollege) = getStudentInfo(); 
Console.WriteLine($"Department: { strDepartment }, College: { strCollege }");

Read also: Selecting, filtering, sorting and pagination in SharePoint REST API.

New way to throw Exception in C# 7.0

In C# 7.0, we can through exceptions in certain places such as expression etc. see below example:

/*this code is copied from msdn official site*/
class Person
{
    public string Name { get; }
    public Person(string name) => Name = name ?? throw new ArgumentNullException(name);
    public string GetFirstName()
    {
        var parts = Name.Split(" ");
        return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException("No name!");
    }
    public string GetLastName() => throw new NotImplementedException();
}

Read also: Difference between Angular 1 VS Angular 2

Ref returns and locals

Just like we can pass things by reference (with the ref modifier) in C#, we can now return them by reference, and also store them by reference in local variables, isn’t it amazing?

public ref int Find(int number, int[] numbers)
{
    for (int i = 0; i < numbers.Length; i++)
    {
        if (numbers[i] == number) 
        {
            return ref numbers[i]; // return the storage location, not the value
        }
    }
    throw new IndexOutOfRangeException($"{nameof(number)} not found");
}

int[] array = { 1, 15, -39, 0, 7, 14, -12 };
ref int place = ref Find(7, array); // aliases 7's place in the array
place = 9; // replaces 7 with 9 in the array
WriteLine(array[4]); // prints 9

We can use it to pass placeholders into big data structures. For example, a game might hold its data in a big allocated array of structs (to avoid garbage collection pauses). Methods can now return a reference directly to such a struct, through which the caller can read and modify it.

Literal improvements:

In C# 7 features, we can use  “_” as a digit separator inside number literals:

var d = 123_456;
var x = 0xAB_CD_EF;

We can put them wherever we want between digits, to improve readability. They have no effect on the value.

Also, one of the C# 7 features introduces binary literals, so that you can specify bit patterns directly instead of having to know hexadecimal notation by heart.

var b = 0b1010_1011_1100_1101_1110_1111;

Read also: What is Angular 2? High-level overview, feature, and fundamentals.

Switch statements with patterns

In C# 7.0 switch statement is more optimal as:

  • We can switch on any type (not just primitive types).
  • Case clauses can have additional conditions on them.
  • Patterns can be used in case clauses.
    switch(shape)
    {
        case Circle c:
            WriteLine($"circle with radius {c.Radius}");
            break;
        case Rectangle s when (s.Length == s.Height):
            WriteLine($"{s.Length} x {s.Height} square");
            break;
        case Rectangle r:
            WriteLine($"{r.Length} x {r.Height} rectangle");
            break;
        default:
            WriteLine("<unknown shape>");
            break;
        case null:
            throw new ArgumentNullException(nameof(shape));
    }

These are several things we should know about this newly extended switch statement:

  • The order of case clauses now matters: Just like catch clauses, case clauses are no longer necessarily disjoint, and the first one that matches gets picked. In the above code, the square case comes before the rectangle case. Also, like catch clauses, the compiler will help you by flagging obvious cases that can never be reached.
  • The default clause is always evaluated last: Even though the null case above comes last, it will be checked before the default clause. This is for compatibility with existing switch semantics. However, for good practice, we should put the default clause at the end.

Note:

All the above feature are listed in Microsoft official website and some of them are already included in Visual Studio 2015 Preview 4. Some of these features may change or disappear by the time the final release comes out.

Please use below comments box to tell us if something is missing or needs to improve. Also, use “Share button” on the top of this article to share this article on social media. For More update follow us on twitterfacebook. Happy coding 🙂

 

 

S Sharif

Founder of Technical Diary. Software engineer and passionate about technologies to learn and share. Crazy about best practices and new technology. I have worked in C#,ASP.NET MVC, HTML5, AngularJs SharePoint and SQL Server. I always try to keep myself updated and learn and implement new technologies. You can connect me on Twitter Facebook LinkedIn.

You may also like...

3 Responses

  1. Bassam Alugili says:

    Thank you a lot! Your explanation has helped me to make C# 7 Cheat Sheet.

    Link:
    https://github.com/alugili/CSharp7Features/blob/master/C%237CheatSheet.pdf

  2. Amantha Erald says:

    where we use C# now a days?

  1. February 23, 2017

    […] Read Also: C# 7 Features and High-level overview. […]

Leave a Reply

Your email address will not be published. Required fields are marked *