Essential C# nameof Operator  Suggest an edit

Basic usage Printing a variable name

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";

Would output


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"!

Table Of Contents
9 nameof Operator
22 Enum
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close