Home > Software engineering >  C# Interface reference to inherited type
C# Interface reference to inherited type

Time:08-14

How can I define the type of child interfece in interface, please see sample code

public interface IParent<T>: IList<T>
{
    <child_interface> Children { get; }
}

public interface IChildA: IParent<SomeType>{}

I want to have in <child_interface> the type of the inherited Interface (IChildA, IChildB...etc)

Is it even possible ?

Thank you in advance

CodePudding user response:

Add a second generic type parameter to the parent interface. You can also include a type constraint too:

public interface IParent<T, TChild> : IList<T>
    where TChild : IParent<T, TChild>
{
    TChild Children { get; }
}

Now use it like this:

public interface IChildA : IParent<SomeType, IChildA> 
{
}

CodePudding user response:

What @DavidG said, but another way is to not use generics:

public interface IParent
{
    List<IChild> Children { get; }
}
  • Related