oscilatingcretin
oscilatingcretin

Reputation: 10919

Get attribute type name without "Attribute"

typeof(UniqueFieldAttribute).Name returns UniqueFieldAttribute, but I want it to return UniqueField. If VS can resolve an attribute to its actual type without the substring Attribute in the name while it's decorating a class element, it seems that I would be able to get that resolvable name from some property on the type object.

I am aware that I could do this...

typeof(UniqueFieldAttribute).Name.Substring(0, typeof(UniqueFieldAttribute).Name.Length - 9)

...but I don't want to.

Upvotes: 2

Views: 700

Answers (1)

Tom Blodget
Tom Blodget

Reputation: 20772

Nope, there isn't a property of the class or object that gives a friendly attribute name. It's a C# language feature. The compiler (and Visual Studio's IntelliSense) looks for a class exactly as it is typed. If none is found, it appends "Attribute" and looks again.

It's a convention to name attribute classes to end in "Attribute" and to use this language feature. But, neither is required.

So, it would be wrong to blindly strip off the last 9 characters of the attribute class name. You can strip off "Attribute" if it is there at the end. However, unless you are generating C# code, it could be confusing because the each .NET language has it's own spec. To the.NET CLR, a type name that has been simplified in this way is no longer the name of the same (or any) type.

Upvotes: 3

Related Questions