[C#] nameof function

Today I'd like to introduce you the neat build-in function called nameof from C# 6.0 and above.

This function comes in handy when you want to obtain the string name of a variable, type or member.
This is often used when logging errors on debug level to include the name of the failing method.

A quick use case example:

var myString = "This is my test string";
MessageBox.Show(string.format("Name of variable: {0}", nameof(myString)));

This will give us an output like this:

Name of variable: myString

So this can be used in logging, but also when accessing members and properties:

public class WildObject
    {
        public string Name { get; set; }
        public string Type { get; set; }
        public int Age;
    }
var propertyString = string.Empty;
var Tiger = new WildObject()
    {
        Name = "YoungTiger",
        Type = "Siberian Tiger",
        Age = 2
    };

propertyString += string.Format("\n{0} => {1}", nameof(Tiger.Name), Tiger.Name);
propertyString += string.Format("\n{0} => {1}", nameof(Tiger.Type), Tiger.Type);
propertyString += string.Format("\n{0} => {1}", nameof(Tiger.Age), Tiger.Age.ToString());
           System.Diagnostics.Trace.Write(propertyString);

Output:

Name => YoungTiger
Type => Siberian Tiger
Age => 2

Reference documentation: MSDN

Robin

Software Engineer / Application Developer

Subscribe to robsCode

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!