JustBrowsing
JustBrowsing

Reputation: 155

C# custom attribute naming

I have a custom Attribute class that I defined as:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class MyCustomAttribute : System.Attribute
{
    ...
}

From the microsoft website:

By convention, the name of the attribute class ends with the word Attribute. While not required, this convention is recommended for readability. When the attribute is applied, the inclusion of the word Attribute is optional.

So, the attribute can be use by either

[MyCustom()]

or

[MyCustomAttribute()]

My question to you all, is if anyone has experienced any problems with using the abbreviated version of the name vs the full name? I am running 4.0 framework.

Thanks!

Upvotes: 11

Views: 3322

Answers (4)

earlNameless
earlNameless

Reputation: 2918

No problems.

Underneath in compiled IL the name always has Attribute appended to it (the full type name).

Based on ECMA-334 (C# spec) 24.2, the resolution is done first by exact match, then by appending "Attribute" to the name given in []. Additionally, if there is a conflict (ex: MyAttribute, and MyAttributeAttribute) a compile time error is generated when "MyAttribute" would be used.

Upvotes: 12

Jon Skeet
Jon Skeet

Reputation: 1500285

It should be fine... I'd just advise you not to introduce two attributes with names only differing by the number of Attribute suffixes:

public class FooAttribute : Attribute { }

public class FooAttributeAttribute : Attribute { }

[FooAttribute] // Could be either!

I suspect the exact match would win here, but please don't introduce the ambiguity in the first place. (I haven't checked the spec.)

Upvotes: 9

Aaron Marten
Aaron Marten

Reputation: 6568

In general, you shouldn't hit any problems. The C# compiler is smart enough to resolve it to the proper type in either case.

Upvotes: 0

sehe
sehe

Reputation: 392921

Nope. Easy as pie!

Also, you can use it without the empty () parentheses

Upvotes: 1

Related Questions