C# and the "nameof" and $ operators
May 18, 2017
.net Programming
Starting with C# version 6, the "nameof" operator was introduced as a means of qualifying names in code. And in c# 7 we got the new $ string prefix.Why should we care about and start using these in our code? For one reason: better code quality. And by "quality" I mean code that is less error-prone and also easier to understand - which is code that every programmer should strive to write.
Let's take a simple code example to show the value of both.
Traditional Code
Prior to these language changes, a simple parameter check could easily introduce two significant bugs over time.
public
void
MyMethod(
string
input)
{
// check the parameter for validity
if
(
string
.IsNullOrWhiteSpace(input))
throw
new
ArgumentException(
string
.Format(
"The parameter {0} has an invalid value {1}."
,
"input"
, (input ==
null
?
"null"
:
"empty"
)),
"input"
);
// everything else...
}
Upon quick analysis, this code look OK (albeit quite trivial). But what happens if you refactor the code and decide to change the name of the "input" parameter? Or, what happens if you change the ArgumentException's message?
Both of these are potential bugs.
Same Code Using nameof / $
Let's rewrite this code to use the new C# language features. The result is this:
public
void
MyMethod(
string
input)
{
// check the parameter for validity
if
(
string
.IsNullOrWhiteSpace(input))
throw
new
ArgumentException($
"The parameter {nameof(input)} has an invalid value {(input == null ? "
null
" : "
empty
")}."
, nameof(input));
// everything else...
}
The changes are subtle, but incredibly important.
Using the nameof operator allows the compiler to emit the parameter name. So if you rename the input parameter to "myInput", two things are now possible. The first is that the compiler will produce an error if the "nameof" statements are not updated with the new parameter name - which forces the exception message to always be in sync with the parameter name. Furthermore, Visual Studio is intelligent enough to actually modify your code for you when you change the parameter name to keep everything in sync. None of this is possible in the Traditional code...
The $ string prefix operator places all of the string formatting inline with the actual string itself. This is important for two reasons. First, if you change the order or number of tokens in the string, String.Format can easily get out of sync and either crash at runtime or produce a garbles message. Second, the code is much easier to read since everything is inline as though it is an actual string - no more counting parameters to figure out {0} or {1} actually represent.
Better Code!
While this example is quite trivial, in reality, both of these language features have saved me time and increased the readability and reliability of my code. I encourage you to start using them!