The nameof operator


Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/lybecker.com/public_html/blog/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524

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.