#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:


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,209 – C# 6.0 – Using the nameof Operator

  1. Pingback: Dew Drop – October 23, 2014 (#1883) | Morning Dew

  2. Pingback: Is nameof() evaluated at compile-time? - BlogoSfera

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: