C# 6.0 Features Series
- How to try C# 6.0 and Rosyln?
- Getter-only (Read Only) Auto Properties in C# 6.0
- Lambda and Getter Only Auto-Properties in C# 6.0
- Initializers for Read-Only Auto Properties in C# 6.0
- Initializers via Expression Auto Properties in C# 6.0
- C# 6.0 – A field initializer cannot reference the non-static field, method, or property
- Lambda Expression for Function Members in C# 6.0
- Dictionary Initializers (Index Initializers) in C# 6.0
- Expression Bodies on Methods returning void in C# 6.0
- using keyword for static class in C# 6.0
- Unused namespaces in Different Color in Visual Studio 2015
- Null-Conditional Operator in C# 6.0
- Null-Conditional Operator and Delegates
- nameof Operator in C# 6.0
- Contextual Keywords in C#
- String Interpolation in C# 6.0
- Exception Filters in C# 6.0
- Await in Catch and finally block in C# 6.0
C# 6.0 introduces the new nameof operator that returns the name of the program element.
For example , assume that you want to throw the ArgumentNullException for a parameter , you would do something like the code snippet shown in the earlier version of C#.
public void PerformAction(Point point1, Point pointy) { if(point1 == null) { throw new ArgumentNullException("point1"); } }
In the above code snippet , the ArgumentNullException takes the parameter of type string with the name of the parameter point1 . Now , if you refactor this method by renaming the parameter point1 to pointx , the parameter of ArgumentNullException still remains as “point1” . This might lead to inconsistency.
The nameof operator solves this problem . You could rewrite the above code snippet as shown below.
public void PerformAction(Point point1, Point pointy) { if(point1 == null) { throw new ArgumentNullException(nameof(point1)); } }
Now , when you rename the first parameter “point1” , the corresponding name used with the nameof operator would also be updated.