5 quick questions on Custom Attributes

1) What are custom attributes?

Attributes are instances of a Type. Attributes are just like any other class object except that they allow some special syntax.

2) Are attributes an alternate way of specifying a base class for a class? Inside an attributed class can I call the attribute’s method just like a base class method?

No. Even from inside an attributed class we cannot call an attribute’s member function without having an attribute object( as in <object>.SomeMethod() ). This sounds like an obvious statement. But this shows that attributes are not ‘base classes’ and an attributed class doesn’t derive from the attribute class. Normally, we will be able to call the base class methods from inside a derived class without having any object( or by using the Base keyword).

3) So, How are attributes connected to a class?

Attributes are some kind of special MEMBERS of the attributed class. Attributes are native to .NET and they get their own semantics. However there don’t seem to be a direct way to access the attribute instances. We have to go through GetCustomAttributes function to get the attribute instance and invoke its methods. ILDasm comes up with this for an attribute

 

.custom instance void Attrib.MyAttrib::ctor() = ( 01 00 00 00 )

 

Attrib is the namespace, MyAttrib the attribute.

4) I have defined my attribute class and applied it to a class. Is that all?

There is no effect on just attributing a class unless somebody\something checks whether a particular attribute is present and do some action based on that. Its like marking a statement in C/C++ with a label. Unless somebody uses a ‘GOTO’ statement, the label is pretty much useless. Using the label alone has no effect on the code.

5) Can I apply attributes only to Classes?

Attributes can be applied to data and method members of a class also. This again means that attributes are some kind of a special entity in .NET and it really doesn’t have any counterparts in classic C++.

 

Refer to Applied Microsoft.NET Framework Programming by Jeffrey Richter for some excellent coverage on Attributes( and lot of other stuff.NET)

Comments

  • Anonymous
    October 19, 2005
    There's also the book, "Applied .NET Attributes", which is most excellent, and shows off non-obvious ways you can make use of them.