Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 675
RichK Avatar asked Dec 09 '25 03:12

RichK


1 Answers

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.

like image 120
Jamiec Avatar answered Dec 10 '25 17:12

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!