I\'m stuck trying to translate some Java code that uses (bounded) wildcard generics to C#. My problem is, Java seems to allow a generic type to be both covariant and contr
You need to translate the Java wildcard generic methods to C# methods that are generic in their own right. For example, this:
interface IGeneric2 {
void method2(IGeneric1> val);
}
should be translated to
interface IGeneric2where T:Impl {
void method2(IGeneric1 val) where U:Impl;
}
It is necessary to repeat the type constraint for T
specified by IGeneric1
as the type constraint for U
.
The reason for this is that in the Java version there are implicit constraints for the type arguments of the parameters of method1
and method2
: if the parameter must be some kind of IGeneric1
then X
must obviously be an Impl
because otherwise it could not possibly implement IGeneric1
for that type.
In C# the constraints must be explicit, so you repeat what IGeneric1
and IGeneric2
require of T
.
So the equivalent code would be:
interface IInterf { }
class Impl : IInterf { }
interface IGeneric1 where T:Impl {
void method1(IGeneric2 val) where U:Impl;
void method1WithParam(T to);
}
interface IGeneric2where T:Impl {
void method2(IGeneric1 val) where U:Impl;
}
abstract class Generic : IGeneric1, IGeneric2 where T : Impl
{
public void method1(IGeneric2 val2) where U:Impl
{
val2.method2(this);
}
public abstract void method1WithParam(T to);
public abstract void method2(IGeneric1 val) where U:Impl;
}