Attributes in base and derived classes

  • Thread starter Thread starter Edward Diener
  • Start date Start date
E

Edward Diener

If I set an attribute on some part of a class, such as a property or event,
does that attribute also apply to the same property or event of a derived
class ?

If the above is true, can I change the attribute of a property or event from
something in a base class to something different in a derived class ?
 
Edward,
If I set an attribute on some part of a class, such as a property or event,
does that attribute also apply to the same property or event of a derived
class ?

It depends on how you look up the attribute, the GetCustomAttribute
reflection methods usually have a boolean parameter to indicate
whether you want to search base class members for attributes as well.

It also depends on the AttributeUsage.Inherited setting of the
attribute class.



Mattias
 
Mattias said:
Edward,


It depends on how you look up the attribute, the GetCustomAttribute
reflection methods usually have a boolean parameter to indicate
whether you want to search base class members for attributes as well.

In that case I would have to know how the attribute is being used by
whomever is using it.
It also depends on the AttributeUsage.Inherited setting of the
attribute class.

Amazingly enough one topic in the MSDN documentation says that the default
value for the Inherited value of AttributeUsageAttribute class is true ( in
the actual .NET framework reference for the class ), while another topic
says that the default value for the Inherited value of the
AttributeUsageAttribute class is false ( C# Programmer's Reference, C#
Attributes ). I tend to believe the former is true, as it is more natural to
believe that if one sets an attribute on an element in a base class, the
same attribute should be applied to the inherited element of the derived
class.

This whole question came about because I wished to be able to change a
property or event in a base class from being browsable to being not
browsable in a derived class. The BrowsableAttribute normally defaults to
true. I was wondering how I can set it to false for a derived class,
especially as I can't just redeclare a given property or event. Is there a
way to apply an attribute to an element of a base class which has been
automatically derived in a derived class ?
 
Back
Top