The nameof expression in C #

The nameof expression allows us to get an string with the name of a namespace, class, method, parameter, property, field or variable. This makes it very useful when we are throwing exceptions.


Let’s see an example without using nameof and another using it:

In our example, in the DoSomething method we verify if the parameter is null and if so, we throw an exception showing the name of the parameter that caused it. So far all right, but what happens if we refactor the name of the parameter?, we would have to change the string of the line 4, without mentioning that we could have some misspelling or in other cases more than one parameter to change.

In the DoSomethingElse method if we do a rename refactoring we do not have any problem, because in line 15 where we throw the exception we are using the nameof expression that reference the parameter name instead of hard-coding .

Example using a dictionary:

In the previous example we have a Settings class that has two auto-implemented properties, where the name of these is used as a key in the dictionary and its content as a value.


The nameof expression get a string based on the name of a variable, type of an object and are quite useful when working with exceptions, although we can use it as we need it.

If you like the post, have any questions or comments, mention me in Twitter @robertlluberes

Leave a Reply