Getting the name of a variable in C# 6 using nameof
February 16, 2016 Leave a comment
C# 6 makes it easy to retrieve the name of a parameter using the nameof keyword. Here comes a situation where it can come handy.
Consider the following Person class with C# 6:
public class Person
{
public int Age { get; }
public string FirstName { get;}
public string LastName { get; }
public Person(string firstName, string lastName, int age)
{
FirstName = firstName;
LastName = lastName;
Age = age;
}
}
Simple, right? Now let’s say you’d like to add some parameter validation to the constructor: