Wednesday, 7 July 2010

Using Attributes


I just realised that we have two ways to use an attribute.

For example the attribute - AttributeUsage - is implemented in the class AttributeUsageAttribute. And we can use either AttributeUsage or AttributeUsageAttribute in our code.

In fact if you create a custom attribute in class named "TestAttribute":

public class TestAttribute : Attribute
{
}

and define another custom attribute named "Test":

public class Test : Attribute
{
}

and then try using the attribute in a class:

[Test()]
public class MyClass
{ }

This will give compilation error:
'Test' is ambiguous between 'Test' and 'TestAttribute'; use either '@Test' or 'TestAttribute'

The code intellisense as well displays only the "Test" pointing to TestAttribute in its list, it doesn't show the other "Test".

I believe C# creates an alias of TestAttribute somewhere for the attribute. It actually makes sense to use aliased-name of attribute. It would be unwieldy to write attributes as WebMethodAttribute, ConditionalAttribute or AttributeUsageAttribute - just to name a few defined in the framework. Microsoft also uses the alias on MSDN.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Shorts - week 3, 2022

Post with links to what I am reading: 1. A very good post on different aspects of system architecture: https://lethain.com/introduction-to-a...