Home
C#
nameof Keyword
This page was last reviewed on Sep 12, 2024.
Dot Net Perls
Nameof. 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.
typeof
sizeof
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.
Example. 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.
So We can use 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
Example 2. 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.
Info We just reference the left and right variables by their names directly. So the compiler checks for spelling mistakes.
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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 12, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.