General class and problems with IEquatable

I want a generic class to implement the IEquatable <T> interface. The class has data members of type T. For a generic class that must be equal, the data members must also be.

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's the problem. When I compile the above generic class I get the following message.

GenericArguments [0], 'T' on 'Myspace.Generic.V`1 [T]' violates parameter type 'T' constraint.

Where can I make a mistake in my reasoning or what is wrong with my general class?

Note: When I leave IEquatable<V<T>>

outside the generic class and the code for public bool Equals(V<T> other)

intact, then the generic class is compiled and can be used. Except for IEquitable detection by the compiler.

public class V<T> where T : IEquatable<T>
{

      

The above code works, but instances are V<T>

no longer recognized as IEquitable

Note 2: Thanks to dasblinkenlight for trying this code in a solution myself, I found out that this is most likely a configuration issue, not a coding issue. Now I am considering this specific question as an answer, but I have not yet defined my config issue.

Note3: The actual cause of the problem is the NUnit test module that loads the DLL through the accessory. Requires a change in testing procedures but is IEquatable<V<T>>

now used without any problems.

The problem has been resolved.

+3


source to share


1 answer


There is nothing wrong with your generic class. There is something wrong with the class you are passing as its general parameter T

. Namely, the SomeClass

class you pass to V<SomeClass>

does not implement IEquitable<SomeClass>

.



The class V<T>

needs to T

be an implementation IEquitable<T>

. This is necessary to test for stepwise equality of arrays using an expression Value[i].Equals(other.Value[i])

. If any class you are using as a V<T>

generic parameter is not fair to yourself, the compiler will complain.

+2


source







All Articles