The nameof
operator allows you to get the name of a variable, type or member in string form without hard-coding it as a literal. The operation is evaluated at compile-time, which means that you can rename, using an IDE's rename feature, a referenced identifier and the name string will update with it.
var myString = "String Contents";
Console.WriteLine(nameof(myString));
Would output
myString
because the name of the variable is "myString". Refactoring the variable name would change the string.
If called on a reference type, the nameof
operator returns the name of the current reference, not the name or type name of the underlying object. For example:
string greeting = "Hello!";
Object mailMessageBody = greeting;
Console.WriteLine(nameof(greeting)); // Returns "greeting"
Console.WriteLine(nameof(mailMessageBody)); // Returns "mailMessageBody", NOT "greeting"!