DefaultValueAttribute
-
Is it possible to change the DefaultValue attribute for a property for a derived class without having to re-define the whole property?
It actually depends on how you plan to use it. Normally, yes, you would have to override the property and attribute it with a different value for the
DefaultValueAttribute
constructor. If the object is only to be used with Component Model clients (like thePropertyGrid
) you can implementICustomTypeDescritor
and when aPropertyDescriptor
is requested for the property you can return a custom implementation that returns a different instance ofDefaultValueAttribute
from thePropertyDescriptor.Attributes
. See the documentation forICustomTypeDescriptor
for more details. You can return the default implementation for most methods you don't need to override using theTypeDescriptor
class (corresponding methods toICustomTypeDescriptor
take an additional parameter that basically says not to use anyICustomTypeDescriptor
implementation). Since you care about theDefaultValueAttribute
and this is generally used at design-time (though not necessary), you could also implement a custom designer that does essentially what I mentioned above. If this was aComponent
derivative you would implement a derivative ofComponentDesigner
and overridePostFilterAttributes
. Generally speaking, though - it's far easier of a change and easier to maintain with less possibility of bugs to just override the property. It could be as easy as the following:public class MyBase
{
bool _boolProperty = true;
[DefaultValue(true)]
public virtual bool BoolProperty
{
get { return _boolProperty; }
set { _boolProperty = value; }
}
}
public class MyDerivative : MyBase
{
public MyDerivative()
{
BoolProperty = false;
}
[DefaultValue(false)]
public override bool BoolProperty
{
get { return base.BoolProperty; }
set { base.BoolProperty = value; }
}
}See, there's nothing really to implement - just set the member of the base class. Many classes within the .NET Framework base class library do this when necessary. It's just a cleaner design and doesn't depend on callers having to implement or use rather difficult interfaces. This posting is provided "AS IS" with no warranties, and confers no rights. Software Design Engineer Developer Division Customer Product-lifecycle Experience Microsoft