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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.