Friday, December 26, 2014

C# 6.0–nameof Operator

This blog post is part of C# 6.0 Features Series.
Microsoft announced the new version of C# 6.0 at the day of visual studio connect event on November. They have not added any big features to C# 6.0 but they have listened to community and added few small features which comes really handy. One of the that is nameof operator.  In this blog post we learn why nameof operator is very useful.

Let’s create a class Employee with few properties.
public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Now what I want to do here is to create a object with object initializer and print values of properties with print method.

Old way of doing this to pass hardcoded string like following.
class Program
{
    static void Main(string[] args)
    {
        Employee employee = new Employee
                            { FirstName = "Jalpesh",
                            LastName = "Vadgama" };
        Print(null);
    }
    static void Print(Employee employee)
    {
        if (employee == null)
            throw new ArgumentException("employee");

        Console.WriteLine(employee.FirstName);
        Console.WriteLine(employee.LastName);
    }
}
Here strings are hardcoded in argument exception so that we have problem because when change names of class we have to change this hardcoded string also.

With nameof operator:


Now let’s do same thing with nameof operator.  Following is a code for that.
class Program
{
    static void Main(string[] args)
    {
        Employee employee = new Employee
                            { FirstName = "Jalpesh",
                            LastName = "Vadgama" };
        Print(null);
    }
    static void Print(Employee employee)
    {
        if (employee == null)
            throw new ArgumentException(nameof(employee));
       
        Console.WriteLine(employee.FirstName);
        Console.WriteLine(employee.LastName);
    }
}
Here you can see that I have used nameof operator in place of hardcoded string so now even if we change the name of class then also we don’t have to worry about it. Now let’s run this and we will see output as expected as we have passed null to print method.

nameof-operator-output

Here we have passed null so it will throw argument exception. You can find complete source code on github at following location.

https://github.com/dotnetjalps/Csharp6NewFeatures

That’s it. Hope you like it. Stay tuned for more!.
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews