0

Is there a way to pass a parameter type that must be an extension of another type? I tried this but that isn't how it is done (I believe).

public class SettingsAttribute : Attribute 
{
    public SettingsAttribute(Type<MyBaseClass> action) 
    { 
    }
}

Valid

public class Dog : MyBaseClass 
{
}

[Settings(typeof(Dog))]
public class ABC 
{
}

Invalid

public class Cat : DoesntExtendMyBaseClass 
{
}

[Settings(typeof(Cat))]
public class ABC 
{
}
maccettura
  • 10,514
  • 3
  • 28
  • 35
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

1 Answers1

0

Type doesn't allows anything like that at all, you can only provide an "unlimited" Type instance and at most validate at runtime that any extra requirements are fulfilled, but the compiler won't help here in detecting problems earlier.

An additional problem your code faces is that the class defines an attribute. Attributes cannot be generic, so you can't use some tricks with generics like in most other situations. Outside of an attribute definitition you would do something like this:

public class Settings<T> where T : MyBaseClass {
    public SettingsAttribute(T action) { }
}

Note that this differs in that it takes an instance of the type, instead of the Type itself.

But neither this is useful in your particular situation. Bottom line: live without the restriction and validate before using. The compiler doesn't offers any other help for this.

Alejandro
  • 7,290
  • 4
  • 34
  • 59