How to use the nameof keyword in C#
The nameof keyword in C# returns the variable, type, or member as a string. The string is resolved during compile time, meaning that using it won't affect our performance.
The benefit of using it is that whenever we have an error message, for example, linked to a variable, the error message is not vulnerable to refactorings.
Usage
Syntax
The syntax for the keyword is pretty simple: nameof(variableName).
Return value
The name of the variable as a string.
Examples and use cases
Let's see how we can use the nameof keyword. We've used accountName in the example below. Try changing the name of the variable and see how it affects the output.
using System;class MainClass{static void Main(){// Declaration of the variablestring accountName = "Foo";// Prints the name of the variable, courtesy of the 'nameof' keywordConsole.WriteLine("The name of the variable is: " + nameof(accountName));// Prints the value of the variableConsole.WriteLine("The value of the variable is: " + accountName);}}
The example above simply demonstrates how to use and the effects of using the nameof keyword. Now let's see some more examples, covering daily use cases for the keyword.
Argument exceptions
using System;class MainClass{static void Main(){// Declaration of the variableint catsAge = 30;// Validates the ageValidateAge(catsAge);// Prints the result of the execution to the userConsole.WriteLine("Method ran successfully!");}static void ValidateAge(int catsAge){// Verifies is under the minimum valueif(catsAge < 0){// Throws an exception with a message and the name of the invalid parameterthrow new ArgumentOutOfRangeException(nameof(catsAge), "Invalid age.");}// Verifies exceeds the maximum valueif(catsAge > 25){// Throws an exception with a message and the name of the invalid parameterthrow new ArgumentOutOfRangeException(nameof(catsAge), "Cats don't live that long, unfortunately.");}}}
PropertyChanged event in WPF
class WildWestCity : INotifyPropertyChanged{// Declares the eventpublic event PropertyChangedEventHandler? PropertyChanged;// Declares the variableprivate string name;public string Name{get { return name; }set{// Stores the value in the variablename = value;// Calls the method that invokes the event, supplying its name as the parameterOnPropertyChanged(nameof(Name));}}// Declares the variableprivate int population;public int Population{get { return population; }set{// Stores the value in the variablepopulation = value;// Calls the method that invokes the event, supplying its name as the parameterOnPropertyChanged(nameof(Population));}}public void OnPropertyChanged(string property){// Invokes the eventPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));}}
Note: The code above is not executable. It is simply an example class to demonstrate how we can possibly use the keyword when implementing
INotifyPropertyChanged.