It provides great opportunity to clean up messy code.
Indeed! There are many occasions where we need C# identifiers to be represented as strings in our code. Here are the most prominent ones:
Parameter names in argument exceptions. E.g. throw new ArgumentNullException("someParameter")
Property names in raising OnPropertyChanged events. E.g. PropertyChanged(this, new PropertyChangedEventArgs("SomeProperty")
Property names in dependency property declarations. E.g. DependencyProperty.Register("SomeProperty", typeof(int), ...)
Property names in Html extensions. E.g. @Html.TextBox("SomeProperty")
Method names in logging. E.g. Log("SomeMethod", "...")
Having hardcoded strings in code as in the examples given above brings the risk of a mismatch in case of refactoring. Besides, it lacks IntelliSense support. (ReSharper tackles well both of the issues, but is a payed tool and in my experience not a standard part of developers toolboxes.)
When LINQ appeared it offered an acceptable alternative to hardcoded strings that brought both IntelliSense and refactoring support - extracting identifier names from expression trees.
Many APIs appeared that offered a possibility to specify identifiers via suitable LINQ expressions. For example
@Html.TextBoxFor(x => x.SomeProperty)
Yet, this approach came with run-time costs and wasn’t always really practical, like e.g. in the case of parameter names in argument exceptions.
C# 6.0 nameof expressions solve all these issues. Over time Sharpen will support all of the cases mentioned above, as well as “hand-made” solutions and idioms based on LINQ expressions. Here is where I see the strength of Sharpen compared to generic static analysis tools. Sharpen has a goal to collect and understand existing patterns over time widely adopted in the community, to recognize them in code and to suggest usage of modern alternatives.
nameof Expressions in Argument Exceptions and Dependency Property Declarations
Sharpen 0.5.0 supports two of the most prominent use cases described above:
Usage of parameter names in argument exceptions.
Usage of property names in dependency property declarations.
As always, it was interesting to see how often these cases appear in real-life code. Our standard sample project, NHibernate, is not a WPF project so we didn’t expect any dependency property declarations to be found. On the other hand, hard coded parameter names in argument expressions appear in NHibernate code many times:
Another analysis run on a large WPF based desktop application demonstrated a huge potential for usage of nameof expressions in dependency property declarations: