Saturday, 7 September 2013

C# Generics : CS0311 when implementing generic class that meets a generic interface contract

C# Generics : CS0311 when implementing generic class that meets a generic
interface contract

I have searched around and found one somewhat relevant answer but, for the
life of me, I still cannot figure out where I'm going wrong! I am trying
to implement some generically typed tree data structures, using code
similar to that below, but I get compiler error CS0311.
error CS0311: The type 'Test.TestType' cannot be used as type parameter
'K' in the generic type or method 'Test.TreeIndex'. There is no implicit
reference conversion from 'Test.TestType' to 'Test.IIndexable'.
I just can't figure out why the compiler doesn't know how to deal with
this so any clues would be much appreciated.
public interface IIndexable<K> where K : IComparable
{
byte[] ToBytes();
K FromBytes(byte[] bytes);
}
public class TestType : IIndexable<byte>, IComparable
{
public int CompareTo(object b)
{
return 1;
}
public byte[] ToBytes()
{
return new byte[1];
}
public byte FromBytes(byte[] bytes)
{
return 0;
}
}
public class TreeIndex<K> where K : IComparable, IIndexable<K>
{
public int SomeMethod(K a, K b)
{
return a.CompareTo(b);
}
}
class Program
{
static void Main()
{
TreeIndex<TestType> treeIndex = new TreeIndex<TestType>(); //
CS0311 generated twice here
}
}

No comments:

Post a Comment