The nameof operator

The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.

The nameof operator takes a class, method, property, field or variable and returns the string literal.

var p = new Person();

Console.WriteLine(nameof(Person));
Console.WriteLine(nameof(p));
Console.WriteLine(nameof(Person.Name));
Console.WriteLine(nameof(Person.HomeAddress));

// Output:
//   Person
//   p
//   Name
//   HomeAddress

This is handy when doing input validation by keeping the method parameter and the parameter name of the ArgumentNullException in sync.

public Point AddPoint(Point point)
{
  if (point == null)
    throw new ArgumentNullException(nameof(point));
}

The nameof operator is useful when implementing the INotifyPropertyChanged interface

public string Name
{
  get
  {
    return _name;
  }
  set
  {
    _name = value;
    this.OnPropertyChanged(nameof(Name));
  }
}

The Chained null checks blog post shows how to simplify triggering event in the OnPropertyChanged with the null-conditional operator.

  • sevenacids

    It’s also useful in WPF dependency property definitions:

    public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register(nameof(Value), typeof(Int32), typeof(SomeClass));

    public Int32 Value {
    get { return (Int32)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
    }