This operator returns a string
with a variable's name. It works at compile-time. It is a special compiler feature that simplifies some programs.
Though we can usually hard-code the names of variables in debugging output, nameof
provides a more elegant solution. It can reduce duplication and thus errors arising from duplication.
The nameof
keyword returns a string
containing the identifier of a variable. This is a compile-time feature. The compiler knows the names of variables, and it inserts them.
nameof
even on local variables. We use it here to get an argument's name (size) and a local's name (animal).using System; class Program { static void Test(int size) { // ... Write argument name with nameof. Console.WriteLine(nameof(size)); Console.WriteLine(size); // ... Use nameof on a local variable. var animal = "cat"; Console.WriteLine(nameof(animal)); } static void Main() { // Call method. Test(100); } }size 100 animal
Consider this example, which writes the names and values of 2 local variables. We do not have the string
literals "left" or "right" in the program.
using System; var left = 100; var right = 200; // Use nameof inside a string interpolation expression. Console.WriteLine($"{nameof(left)} {left} {nameof(right)} {right}");left 100 right 200
With nameof
, we can use the C# compiler to check that the names of variables are correct when we write them to debug output. We do this by referencing the variable itself.