Novice Student
Novice Student

Reputation: 147

Overriding attributes for inherited fields

Assume I have a class:

abstract class MyBaseClass {

   [Attribute1]
   [Attribute2]
   public string Property1 {get; set; }

   [Attribute3]
   [Attribute4]
   public string Property2 {get; set; }
}

In the child class, that extends this class I want to add new attributes to the Property1 and Property2, preserving attributes, declared in the parent class.

Is this possible?

Upvotes: 1

Views: 318

Answers (3)

adjan
adjan

Reputation: 13652

It is only possible if the attribute that you want to inherit is not specified with AttributeUsageAttribute.Inherited = false. For example, inherting the ObsoleteAttribute does not work:

abstract class MyBaseClass {

   [Obsolete]
   public virtual string Property1 {get; set; }

}

class Derived : MyBaseClass
{
    public override string Property1 {get; set;}
}

In this example, you get the warning message:

Member 'Property1' overrides obsolete member 'Property1'. Add the Obsolete attribute to 'Property1'

By default, attributes are set with the Inherit = True flag. So if you create a custom attribute, inheritance should work fine.

Upvotes: 0

MikkaRin
MikkaRin

Reputation: 3084

abstract class MyBaseClass {

   [Attribute1]
   [Attribute2]
   public virtual string Property1 {get; set; }

   [Attribute3]
   [Attribute4]
   public virtual string Property2 {get; set; }
}

class NewClass:MyBaseClass
{
  [Attribute5]
  public override string Property1 {get;set;}

  [Attribute6]
  public override string Property2 {get;set;}
}

Ensure, that Attributes 1-4 use inherited = true

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class Attribute1 : Attribute
{
}

Upvotes: 2

InBetween
InBetween

Reputation: 32740

Yes, you can do this overriding Property1 and Property2. You obviously need to make them virtual in the base class:

class MyAttribute: Attribute {}
class YourAttribute: Attribute {}

class Base
{
    [My]
    public virtual void Foo() {}
}

class Derived: Base 
{
    [Your]
    public override void Foo()
    {
    }
}

And now var attributes = typeof(Derived).GetMethod("Foo").GetCustomAttributes(); will return both MyAttribute and YourAttribute instances of Derived.Foo.

Do note that all GetAttribute type methods have an overload that lets you specify if you want inherited attributed to be included in the result or not. Default behavior is to include inherited attributes.

Upvotes: 1

Related Questions