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:

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.

C# Reactive Extensions - Buffer and Window

I was going through Buffer and Window in RX, thought a few examples would help clear the differences. First create a buffer of even numbe...