nameof expression

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

In C# there is a very handy expression – typeof – that returns the Type of an object. For example:

if(someObject.GetType() == typeof(MyClass))
  DoSomething(someObject);

(Not very OO, but there are times when it is really helpful).

C# 6 adds a similar operator – nameof – which returns the name of an object:

Console.WriteLine("The variable name is " + nameof(someObject));

>>The variable name is someObject

Although there aren’t a ton of situations where this is needed, it is really helpful when dealing with things like logging and exceptions. For example:

private void DoSomething(Customer cust)
{
  if(cust == null)
    throw new ArgumentNullException(nameof(cust));
}

Of course, you could always explicitly provide the name, but if you rename the argument, it is very easy to forget to update a constant string. This could also be used when dealing with raising events, a la WPF, where you want to fire a changed event for a specific property.

Note that even if the object is fully qualified, only the name itself will be returned:

Console.WriteLine("The variable name is " + 
    nameof(SomeClass.SomeProperty));

>>The variable name is SomeProperty

 

Here are links to posts about other new features in C# 6.0:

Leave a Reply

Your email address will not be published. Required fields are marked *

*