Getting the name of a variable in C# 6 using nameof

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.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: