TruMan1
TruMan1

Reputation: 36108

How to require custom attribute from base class?

I have a base class that I would like all derived classes to put an attribute on top of the class like this:

[MyAttribute("Abc 123")]
public class SomeClass : MyBaseClass
{
  public SomeClass() : base()
  {
  }
}


public class MyBaseClass
{
  public string PropA { get; set; }

  public MyBaseClass()
  {
    this.PropA = //ATTRIBUTE VALUE OF DERIVED
  }
}

How do I enforce that derived classes need the attribute, then use the attribute value in the base constructor?

Upvotes: 1

Views: 2193

Answers (4)

Parimal Raj
Parimal Raj

Reputation: 20585

You can throw exception in constructor if a certain attribute is not found.

Sample :

static void Main(string[] args)
{
    MyClass obj =new MyClass();
}

public class MyClassBase
{
    public MyClassBase()
    {
        bool hasAttribute = this.GetType().GetCustomAttributes(typeof(MyAttribute), false).Any(attr => attr != null);

        // as per 'leppie' suggestion you can also check for attribute in better way
        // bool hasAttribute = Attribute.IsDefined(GetType(), typeof(MyAttribute));
        if (!hasAttribute)
        {
            throw new AttributeNotApplied("MyClass");
        }
    }
}

[MyAttribute("Hello")]
class MyClass : MyClassBase
{
    public MyClass()
    {

    }
}

internal class AttributeNotApplied : Exception
{
    public AttributeNotApplied(string message) : base(message)
    {

    }
}

internal class MyAttribute : Attribute
{
    public MyAttribute(string msg)
    {
        //
    }
}

Upvotes: 3

leppie
leppie

Reputation: 117280

What AppDeveloper said, but instead of that monstrosity of code, use

bool hasAttribute = Attribute.IsDefined(GetType(), typeof(MyAttribute));

Upvotes: 2

Piotr Stapp
Piotr Stapp

Reputation: 19820

Maybe instead of using custom attribute use abstract class with abstract property. Using this method you ensure that every non-abstract derived class will implement this property. Simple example is on MSDN

Upvotes: 5

Steven V
Steven V

Reputation: 16595

As far as I know there is no way to force the use of an attribute in C# at compile time. You could check the presence of the attribute at runtime using reflection, but that could be worked around if someone catches the exceptions correctly.

Upvotes: 1

Related Questions