Search code examples
c#attributesambiguity

How to fix Attribute ambiguity


In c#, attributes named SomethingAttribute can be used with the name Something or SomethingAttribute.

It's lead to an ambiguity when there are two different attributes named SomethingAttribute and SomethingAttributeAttribute, what does SomethingAttribute stand for ?

Example:

class MyAttribute : Attribute
{
}

class MyAttributeAttribute : Attribute
{
}

[MyAttribute]  // Here an ambiguous reference.
class A
{

}

I can use [My] or [MyAttributeAttribute] to be sure I use the first or second attribute.

But what if I add a third attribute named MyAttributeAttributeAttribute ?


Solution

  • The simplest solution is to use the @-quoted verbatim.

    [@MyAttribute]
    [@MyAttributeAttribute]
    [@MyAttributeAttributeAttribute]
    class Test
    {
    }
    

    You can also rename them with using :

    using Attribute1 = MyAttribute;
    using Attribute2 = MyAttributeAttribute;
    using Attribute3 = MyAttributeAttributeAttribute;
    
    ...
    
    [Attribute1]
    [Attribute2]
    [Attribute3]
    class Test
    {
    
    }