Marek Legris
Marek Legris

Reputation: 123

Type constraints with type stored in a variable

I'm trying to write a function that takes a parameter of a type that can be defined in a child class.

example:

public abstract class Base
{
    public abstract Type ComponentTypeNeeded { get; }
    public abstract void Do(ComponentTypeNeeded component);
}

what I tried:

public abstract class Base
{
    public abstract Type ComponentTypeNeeded { get; }
    public abstract void Do<T>(T component) where T : ComponentTypeNeeded;
}

That obviously didn't work, which sense to me but I couldn't think of any other solution.

I hope someone here can help me, so thanks in advance!

Upvotes: 1

Views: 47

Answers (1)

Dave
Dave

Reputation: 3017

public abstract class Base<T>
{
    public abstract void Do(T component);
}

That should give you everything you need. Just create an sub class like this example

public class SubClass: Base<string>
{
    public override void Do(string component)
    {
        //implementation
    }
}

Upvotes: 3

Related Questions