Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net 4 generics question

I have the following class structure:

public class A : AInterface { }
public interface AInterface { }

public class B<T> : BInterface<T> where T : AInterface 
{
    public T Element { get; set; }
}
public interface BInterface<T> where T : AInterface 
{
    T Element { get; set; }
}

public class Y : B<A> { }

public class Z<T> where T : BInterface<AInterface> {}

public class Test
{
    public Test()
    {
        Z<Y> z = new Z<Y>();
    }
}

This gives me the following compile erorr in C# 4.0. The type 'Test.Y' cannot be used as type parameter 'T' in the generic type or method 'Test.Z'. There is no implicit reference conversion from 'Test.Y' to 'Test.BInterface'.

I though the covariance in generics should make this work? Any help will be appreciated.

like image 497
roger Avatar asked Jul 23 '26 06:07

roger


1 Answers

Generic parameters in interfaces are invariant by default, you need to explicitly specify whether you want a particular generic parameter to be covariant or contravariant. Basically, in your example you need to add "out" keyword to the interface declaration:

public interface BInterface<out T> where T : AInterface { } 

You can find more info about creating variant interfaces on MSDN: Creating Variant Generic Interfaces (C# and Visual Basic).

like image 143
Alexandra Rusina Avatar answered Jul 28 '26 14:07

Alexandra Rusina



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!