Tuesday 7 November 2017

nameof Expression in C# 6.0

In this article, We will discuss How to use nameof Expression in C# 6.0.

Whenever we used any property, function or a data member name into a message as a string so we need to use the name as hard-coded in “name”. So in the Future if we want to change the message then in all the places we need to change. To avoid this problem, in C# 6.0 nameof expression was developed.

For Example
       class Employee
        {
            public int Id { getset; } = 101;
            public string Name { getset; } = "Max";
            public int Salary { getset; } = 1000;
        }
  static void Main(string[] args)
   {
       Employee objEmp = new Employee();
            Console.WriteLine("{0} : {1}"nameof(Employee.Id), objEmp.Id);
       Console.WriteLine("{0} : {1}"nameof(Employee.Name), objEmp.Name);
       Console.WriteLine("{0} : {1}"nameof(Employee.Salary), objEmp.Salary);  
   }

Output:
       Id : 101
       Name : Max

       Salary : 1000


Whenever we use nameof(Employee.Id) then automatically in the output it will display Id. So no need of any hard-code anything here.

0 comments:

Post a Comment