C# | nameof Operator
Explain what is nameof and the common used cases
By using the nameof
operator, we can easily get the name of a class, method, or variable. It simply returns a string.
It’s commonly used when we want to reuse the name of a property. There are numeric cases where we would want to have the name of the property. The is a very useful way to keep our code bug free as much as possible.
For example:
Handling a property changed event
Take this example, we want to do something based on what property has changed in a switch statement.
switch (e.PropertyName)
{
case nameof(SomeProperty):
{ break; }
}
If we renamed the SomeProperty
, the compiler will throw an error and force us to both the property definition and the nameof(SomeProperty)
expression.
As opposed to the string property
switch (e.PropertyName)
{
// opposed to
case "SomeOtherProperty":
{ break; }
}
When using case "SomeProperty"
, either renaming the SomeOtherProperty
or change the "SomeOtherProperty
the string will result in silently broken runtime behavior, with no errors on the build time.
Argument Exception Handling
It’s also really useful for argument-related exceptions, such as ArgumentException
.
public string DoSomething(string input)
{
if(input == null)
{
throw new ArgumentNullException(nameof(input));
}
}
Now if we want to refactor the name of the input
property parameter, the compiler will also force us to keep the ArgumentNullException(nameof(input))
up to date.