Search code examples
c#genericstype-parameter

Use a Type Defined in Generic Type


Apologies for the title - I really can't think of a very good way to describe my requirement.

I want to be able to define a generic interface (or class, it doesn't matter) whereby the Type parameter supplies another Type which can be accessed from the class. Hopefully this code snippet will explain.

interface IFoo
{
   TOtherType DependentType { get; }
}

interface IMyGeneric<TBar> where TBar : IFoo
{
   TBar ReturnSomeTBar();
   TBar.DependentType ReturnSomeTypeOnTBar();
}

So in this example I want a class to realise IFoo (e.g. Foo) and expose another type, DependentType (e.g. int) so I can use IMyGeneric<Foo> that has methods:

public Foo ReturnSomeTBar()
{
}

public int ReturnSomeTypeOnTBar()
{
}

Clearly the above code doesn't compile so is there a way to achieve this behaviour of generic chaining?


Solution

  • First off, IFoo would need to be generic too

    interface IFoo<TDependent>
    {
       TDependent DependentType { get; }
    }
    

    Then IMyGeneric would need to have 2 type params

    interface IMyGeneric<TBar,TDependent> where TBar : IFoo<TDependent>
    {
       TBar ReturnSomeTBar();
       TDependent ReturnSomeTypeOnTBar();
    }
    

    Perhaps this gets you closer to the solutin you;re after.