I want a generic class to implement the IEquatable<T> interface. The class has data items of type T. For the generic class to be equatable the data items need to be that as well.
Here is my generic class:
public class V<T> : IEquatable<V<T>> where T : IEquatable<T>
{
public V(T[] Value)
{
this.Value = Value;
}
T[] Value { get; set; }
public bool Equals(V<T> other)
{
if (Value.Count() != other.Value.Count()) return false;
for (int i = 0; (i < Value.Count()) && i < other.Value.Count(); i++)
{
if (!Value[i].Equals(other.Value[i])) return false;
}
return true;
}
}
And here is the problem.
When I compile the above generic class I get the following message.
GenericArguments[0], ‘T’ on ‘Myspace.Generic.V`1[T]’ violates the constraint of type parameter ‘T’.
Where do I make the mistake in my reasoning or what is wrong with my generic class?
Note:
When I leave IEquatable<V<T>> out at the generic class and the code for public bool Equals(V<T> other) intact then the generic class compiles and is usable. Except for detecting IEquitable by the compiler.
public class V<T> where T : IEquatable<T>
{
The above code works but instances of V<T> are no longer recognised as IEquitable
Note2:
Thanks to dasblinkenlight for trying this code in a solution on its own I found out that it is most likely a configuration problem and not a coding problem. I now consider this specific question as answered but I’ve not yet identified my configuration problem.
Note3:
The actual cause of the problem is an NUnit test module that loads the dll through an accessor. Changing the test procedures is required but IEquatable<V<T>> is now used wihtout any problems.
Problem Solved.
There is nothing wrong with your generic class. Something is wrong with the class that you are passing as its generic parameter
T. Namely,SomeClass, the class that you pass inV<SomeClass>does not implementIEquitable<SomeClass>.Your
V<T>class requiresTto be an implementation ofIEquitable<T>. You need it in order to check element-by-element equality of arrays using theValue[i].Equals(other.Value[i])expression. If whatever class that you use asV<T>‘s generic parameter is not equitable to itself, the compiler would complain.