Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# attribute that can only be on a method within a class with another attribute

In C# is it possible to put a restriction on an attribute so that it can only be on a method within a class that has another attribute?

[MyClassAttribute]
class Foo
{
    [MyMethodAttribute]
    public string Bar()
}

Where "MyMethodAttribute" can only be inside of a class that has "MyClassAttribute".

Is that possible? If so, how can it be done?

like image 740
Schuyler Avatar asked Jan 31 '26 11:01

Schuyler


1 Answers

If you were going to try a run time validation of your method attributes, you could do something like this:

public abstract class ValidatableMethodAttribute : Attribute
{
    public abstract bool IsValid();
}

public class MyMethodAtt : ValidatableMethodAttribute
{
    private readonly Type _type;

    public override bool IsValid()
    {
        // Validate your class attribute type here
        return _type == typeof (MyMethodAtt);
    }

    public MyMethodAtt(Type type)
    {
        _type = type;
    }
}

[MyClassAtt]
public class Mine
{
    // This is the downside in my opinion,
    // must give compile-time type of containing class here.
    [MyMethodAtt(typeof(MyClassAtt))]
    public void MethodOne()
    {

    }
}

Then use reflection to find all ValidatableMethodAttributes in the system, and call IsValid() on them. This isn't very reliable and is fairly brittle, but this type of validation could achieve what you are looking for.

Alternatively pass the type of the class ( Mine ), then in IsValid() use reflection to find all Attributes on the Mine type.

like image 185
GEEF Avatar answered Feb 02 '26 23:02

GEEF