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:
public Person(string firstName, string lastName, int age) { if (string.IsNullOrEmpty(firstName)) throw new ArgumentNullException("firstName"); if (string.IsNullOrEmpty(lastName)) throw new ArgumentNullException("lastName"); if (age <= 0) throw new ArgumentException("age"); FirstName = firstName; LastName = lastName; Age = age; }
I hope that's also easy to follow. We can test as follows:
Person p = new Person("John", "", 28);
Sure enough, an exception will be thrown:
Value cannot be null.
Parameter name: lastName
That is fine so far. Now let's say that you entirely reshuffle the Person class. Here I'll only show the constructor with the new parameters, you'll get the idea what they are used for:
public Person(string fullName, string address, int numberOfFriends) { if (string.IsNullOrEmpty(fullName)) throw new ArgumentNullException("firstName"); if (string.IsNullOrEmpty(address)) throw new ArgumentNullException("lastName"); if (numberOfFriends <= 0) throw new ArgumentException("age"); FullName = fullName; Address = address; NumberOfFriends = numberOfFriends; }
We effectively pretend that you forget to update the parameter names in the exception constructors.
The call…
Person p = new Person("John Smith", "", 28);
…will again throw the same exception above and the caller may wonder about the "lastName" parameter. What last name?
In C# 6 you can extract the name of a variable with nameof as follows:
if (string.IsNullOrEmpty(fullName)) throw new ArgumentNullException(nameof(fullName)); if (string.IsNullOrEmpty(address)) throw new ArgumentNullException(nameof(address)); if (numberOfFriends <= 0) throw new ArgumentException(nameof(numberOfFriends));
Refactoring to new names will be a lot easier this way and you won't depend on strings for variable names. The exception message will be clear again:
Value cannot be null.
Parameter name: address
View all various C# language feature related posts here.