New feature of C# that I've discovered

Hello everybody,

today I want to describe one new feature of C# that I discovered today. At MSDN it is named Type pattern. It looks like this:

   expr is type varname 

such code gives you to shorter your code.

Take a look at the following code:

using System;

public class Student : IComparable
{
    public String Course { get; set; }
    public int Id { get; set; }

    public int CompareTo(Object o)
    {
        if (o is Student)
        {
            e = o as Student;
if(e == null)
{
throw new ArgumentException("some explanatory error message");
}
return Course.CompareTo(e.Course); } throw new ArgumentException("o is not an Employee object."); } }

Have you ever had such a code? I suppose yes. 

Have you ever wanted to make it shorter? Independently of the answer now you can make it shorter like this:

using System;

public class Student : IComparable
{
    public String Course { get; set; }
    public int Id { get; set; }

    public int CompareTo(Object o)
    {
        if (o is Student e)
        {
            return Course.CompareTo(e.Course);
        }
        throw new ArgumentException("o is not an Employee object.");
    }
}

Take note of e letter in the end of if. For now C# not just check the type, but also will assign value of checked type into varaible. 

One more detail. In case if you work with Visual Studio 2015 most probably VS 2015 will not be able to compile code with Type pattern. In order to educate VS 2015 to know about new features of C# 7 you'll need ask VS 2015 to use newer versoin of C# compiler. In order to do this you'll need to execute following command in package manager console:

Install-Package Microsoft.Net.Compilers

Unfortunatelyy after that command red squiglings will not disapper from your code, but VS 2015 will become able to successfully build your project and execute it.

No Comments

Add a Comment