Matias Cicero
Matias Cicero

Reputation: 26281

Inferring Type from a Type's Base Class in a Generic Class

I know the title may be a little confusing, but let me explain what I'm trying to accomplish..


Let's suppose I have the class

public class TestA<T>
{
    public T Key { get; set; }
}

And the class

public class TestB : TestA<int>
{
    public string Name { get; set; }
}

As you can see, TestB inherits from TestA<int>, and therefore inherits the property public int Key


Now, let's add an interface

public interface TestC<T> where T : TestA<X>
{
    T DoSomething(X argument);
}

And here's where I'm having trouble.

I want the DoSomething method, to take an argument of whatever the type the super class of T (TestA<>) is, in the case of TestB, that would be int.

So, if I had an implementation of type TestC<TestB>, I want the DoSomething signature to be:

public TestB DoSomething(int argument);

The problem is that TestA<X> does not compile and I can't manage to achieve this


Please, do you know if this is possible to do? If so, could you explain me how?

Maybe I can manage something with Reflection?

Upvotes: 0

Views: 162

Answers (2)

Matias Cicero
Matias Cicero

Reputation: 26281

There is a possible solution too:

public interface TestC {
    T DoSomething<T,X>(X x) where T : TestA<X>;
}

public class TestCImpl : TestC {
    public T DoSomething<T,X>(X x) where T : TestA<X>
        //Do something
        return default(T);
    }
}

This one compiles, but is easy to get runtime exceptions, due to the fact that IntelliSense does not seem to work and infer the x argument's type.

For instance, both of these compiles:

TestC c = new TestCImpl();
c.DoSomething<TestB>(2);
c.DoSomething<TestB>("Hello");

But only the first one should really work, as TestB inherits from TestA<int>

Upvotes: -1

Servy
Servy

Reputation: 203802

You simply need to add the generic argument for the type you're missing, in this case, X:

public interface TestC<T, X> where T : TestA<X>
{
    T DoSomething(X argument);
}

Upvotes: 2

Related Questions