Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested generic interfaces

I have a schema of interfaces like the following (C# .NET4)

interface A 
{

}

interface B 
{
    List<A> a;
}

interface C 
{
    List<B> b;
}

and I implemented it in this way:

public interface A 
{

}

public interface B<T> where T : A 
{
    List<T> a { get; set; }
}

public interface C<T> where T : B
{
    List<T> b { get; set; } // << ERROR: Using the generic type 'B<T>' requires 1 type arguments
}

I don't know how to avoid the error Using the generic type 'B' requires 1 type arguments

like image 635
Davide Avatar asked Jan 24 '13 09:01

Davide


People also ask

What is generic interface?

Generic Interfaces in Java are the interfaces that deal with abstract data types. Interface help in the independent manipulation of java collections from representation details. They are used to achieving multiple inheritance in java forming hierarchies. They differ from the java class.

When would you use a generic interface?

It's often useful to define interfaces either for generic collection classes, or for the generic classes that represent items in the collection. To avoid boxing and unboxing operations on value types, it's better to use generic interfaces, such as IComparable<T>, on generic classes.

Can you create an instance of generic interface?

Constructing an Instance of a Generic Type You cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.

Can we have generic interface in C#?

You can declare variant generic interfaces by using the in and out keywords for generic type parameters. ref , in , and out parameters in C# cannot be variant. Value types also do not support variance. You can declare a generic type parameter covariant by using the out keyword.


2 Answers

Since interface B<T> is generic, you need to provide a formal type argument for it when declaring interface C<T>. In other words, the current problem is that you are not telling the compiler what type of interface B interface C "inherits" from.

The two Ts will not necessarily refer to the same type. They can be the same type, as in

public interface C<T> where T : B<T>, A { ... }

or they can be two distinct types:

public interface C<T, U> where T : B<U> where U : A { ... }

The restrictions on the type argument are of course tighter in the first case.

like image 171
Jon Avatar answered Oct 22 '22 11:10

Jon


C looks like Generic Generic type (for lack of a better word).

Would this definition of C work instead?

public interface C<T,U> where T : B<U> where U : A
{
    List<T> b{ get; set; } 
}
like image 22
Srikanth Venugopalan Avatar answered Oct 22 '22 12:10

Srikanth Venugopalan