What about cases where you want to reuse the name of a property, for example when throwing exception based on a property name, or handling a PropertyChanged
event. There are numerous cases where you would want to have the name of the property.
Take this example:
switch (e.PropertyName)
{
case nameof(SomeProperty):
{ break; }
// opposed to
case "SomeOtherProperty":
{ break; }
}
In the first case, renaming SomeProperty
will cause a compilation error if you don't change both the property definition and the nameof(SomeProperty)
expression. In the second case, renaming SomeOtherProperty
or altering the "SomeOtherProperty"
string will result in silently broken runtime behavior, with no error or warning at build time.
This is a very useful way to keep your code compiling and bug free (sort-of).
(A very nice article from Eric Lippert why infoof
didn't make it, while nameof
did)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…