Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing an interface with a generic constraint

Tags:

c#

generics

Bit surprised why this does not work

Is this a limitation of the compiler or does it make good sense not to support it?

public class Class1<T> : IInterface
    where T : Test2
{
    public T Test { get; private set; }
}

public class Test2
{
}

internal interface IInterface
{
    Test2 Test { get; }
}

The error I get is

'ClassLibrary1.Class1<T>' does not implement interface member 'ClassLibrary1.IInterface.Test'. 
'ClassLibrary1.Class1<T>.Test' cannot implement 'ClassLibrary1.IInterface.Test' because it does not have the matching return type of 'ClassLibrary1.Test2'.
like image 467
buckley Avatar asked Oct 10 '12 11:10

buckley


1 Answers

For more corrective, implement interface explicitly:

public class Class1<T> : IInterface
where T : Test2
{
    public T Test { get; private set; }

    Test2 IInterface.Test
    {
        get { ... }
    }
}

Then you can avoid compiled error.

like image 189
cuongle Avatar answered Sep 28 '22 18:09

cuongle