#1,209 – C# 6.0 – Using the nameof Operator

C# 6.0 adds a nameof operator that accepts the name of some program element and returns a string representing the name of the element.  The nameof operator can take as a parameter:

  • Class names
  • Class members
  • Method names
  • Variables

Below, the ShowoffNameof method reports the names of various program elements within the Dog class.  This avoids having to explicitly use reflection to access the names of things.

    public class Dog
    {
        public string Name { get; set; }

        public Dog(string name)
        {
            Name = name;
        }

        public string ShowoffNameof(int myInteger, string myString)
        {
            StringBuilder sbOut = new StringBuilder();

            sbOut.AppendLine(string.Format("Class: {0}", nameof(Dog)));
            sbOut.AppendLine(string.Format("Method: {0}", nameof(ShowoffNameof)));
            sbOut.AppendLine(string.Format("Name prop: {0}", nameof(Name)));
            sbOut.AppendLine(string.Format("1st param: {0}", nameof(myInteger)));
            sbOut.AppendLine(string.Format("2nd param: {0}", nameof(myString)));
            sbOut.AppendLine(string.Format("Local variable: {0}", nameof(sbOut)));

            return sbOut.ToString();
        }
    }

Here’s the output:
1209-001

Advertisements