Home Why you should use nameof()
Post
Cancel

Why you should use nameof()

The nameof() expression has been around for quite some time now, but I still stumble upon situations where nameof() would have been a great fit. Let me tell you about why I use it.

What does nameof() do?

The only thing nameof() does is swapping the parameter name for a string at compile time. A parameter can be a type, method, property or a variable.

1
2
3
4
nameof(MyWebApp.Models.MyModel) // results in "MyModel"
nameof(MyMethod)                // results in "MyMethod"
nameof(MyModel.SomeProperty)    // results in "SomeProperty"
nameof(someParameter)           // results in "someParameter"

This isn’t really spectacular, is it?

The benefits

The benefit of using nameof() is that it prevents you from making typos and also forgetting to change occurrences when refactoring. Because the expression does its job at compile time, the compiler will give an error when the parameter passed into nameof does not exist.

Method parameters

Consider you are using a guard clause in your code that checks a method parameter in your code. If the value of the parameter is invalid, you throw an ArgumentException, like this:

1
2
3
4
5
6
7
public void OrderTickets(int numberOfTickets)
{
    if(numberOfTickets < 1)
        throw new ArgumentException("Cannot order less than 1 ticket", "numberOfTickets");

    // ...
}

Now, lets say we want to change the name of the parameter numberOfTickets to quantity, we do so in the method signature and in the if statement in the next line. And because your boss has a really bad day and demands you to check-in the changes ASAP, we forget to change the parameter name in the string passed to the ArgumentException constructor.

When calling the method with a quantity of 0, and exception is thrown telling us the problem is in the parameter numberOfTickets. If you would have used nameof(numberOfTickets), you would have spotted the error on compile time, since the compiler cannot find numberOfTickets.

1
2
// The compiler would have spotted the error
throw new ArgumentException("Cannot order less than 1 ticket", nameof(numberOfTickets));

UrlHelper in ASP.NET MVC

When you have worked with ASP.NET MVC you have probably used the UrlHelper to link to an action of a controller.

1
Url.Action("Details")

Those calls can be scattered through multiple views and it’s often hard to track down the usages. With nameof(), the compiler quickly finds all the errors:

1
Url.Action(nameof(ProductController.Details))

Reflection

todo

Logging

todo

For further reading, check the documentation at Microsoft Docs

This post is licensed under CC BY 4.0 by the author.
Trending Tags
Contents

-

-

Trending Tags