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.
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 { get; set; } = 101;
public string Name { get; set; } = "Max";
public int Salary { get; set; } = 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