In The craft
A Gotcha: MyName and MyNameAttribute are not the Same!
I spent hours on this one.
I created a custom attribute, lets call it “MyName”. With the attribute ‘MyName’ I want to assign a different name to the property. Normally I would just use the property name, in this case I did not wish too. ‘MyName’ has a property called “Name”. When I extract values from the class I’ll look for the ‘MyName’ attribute, if it exists I’ll use it as the key instead of the property name.
Here is the code:
private string GetName(PropertyDescriptor info)
{
string name = info.Name;
var attributes = info.Attributes.OfType<MyName>();
foreach (var newName in attributes)
{
name = newName.PropertyName;
break;
}
return name;
}
Looks good? The code compiles. It even runs! But an attribute will never be found.
I am looking for attribute of MyName. In .Net land when attributes are created the class is typically names ‘Something’ plus ‘Attribute’, yet when you use them, they are used it’s simply ‘Something’. When I am looping through the Attributes collection I am looking for the type of MyNameAttribute, not MyName. The Kicker is that it compiles, in reality there is not a class called ‘MyName’(I’m sure it’s created at compile time, but I am not talking about that).
Working code:
private string GetName(PropertyDescriptor info)
{
string name = info.Name;
var attributes = info.Attributes.OfType<MyNameAttribute>();
foreach (var newName in attributes)
{
name = newName.PropertyName;
break;
}
return name;
}