The nameof expressions

The nameof expressions are particularly nice. You can now provide a string that names an object in code. This is especially handy if you are throwing exceptions. You can now see which variable caused the exception. In the past, developers had to rely on messy string literals in their code. This was particularly error prone and vulnerable to spelling errors. Another problem was that any code refactoring might miss a string literal, and then that code becomes obsolete and broken.

The nameof expressions have come to save the day. The compiler will see that you are referencing the name of a specific variable and correctly convert it to a string. nameof expressions, therefore, also stay in sync with any refactoring you may do. ...

Get C# Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.