Frank Merrow
Frank Merrow

Reputation: 1009

What "where" clause will make this Generic Method work?

Consider this admittedly contrived Generic Definition:

    private void Foo<T,BASETYPE>(PropertyInfo prop, BASETYPE o1, BASETYPE o2)
    {
        T value1 = (T) prop.GetValue(o1, null);
        T value2 = (T) prop.GetValue(o2, null);
        if (value1 != value2)
            Console.WriteLine("NOT EQUAL");
    }

prop is guaranteed to be a PropertyInfo for BASETYPE.

I am getting a compile error at the if() statement:

Operator '!=' cannot be applied to operands of type 'T' and 'T'

While in the "general case" I understand that the error message is valid, in this case, I only want the routine for some of the standard types: System.Int64, System.String, etc all of which support the == and != operator.

I assume this can be fixed with a "where" clause, but IComparable and IEqualable don't help.

Do anyone know what the correct "where" clause is?

Frank

Upvotes: 0

Views: 517

Answers (5)

Matt H
Matt H

Reputation: 7389

You can use the Equals() instance method that all types have, the static Object.ReferenceEquals() or Object.Equals() methods, or you could use the EqualityComparer<T>.Default.Equals() method.

Upvotes: 0

Bala R
Bala R

Reputation: 109027

Since System.Int64, System.String, etc .. from your list implement IComparable, you could use

where T : IComparable

and use CompareTo() instead of !=

For eg. this code would compile

private void Foo<T>(object o) where T : IComparable
{
    T v1 = default(T);
    T v2 = default(T);
    if(v1.CompareTo(v2)  != 0)
    {
        Console.WriteLine("Not Equal");
    }
}

private void Bar()
{
    Foo<string>(new object());
}

Upvotes: 4

Ritch Melton
Ritch Melton

Reputation: 11618

I don't think you can. There's no such thing as an operator constraint, so there's no way to tell the compiler that it should only allow objects with the != operator to be called. You can use the .Equals method because that's in the base object class.

Here's an article discussing operator constraints: Operator Constraints

Upvotes: 0

Ben M
Ben M

Reputation: 22522

If you're willing to accept a performance hit, you can use

if (Comparer<T>.Default.Compare(value1, value2) == 0))
{
    Console.WriteLine("NOT EQUAL");
}

Upvotes: 0

luqui
luqui

Reputation: 60543

I don't think there is one, unfortunately. You need to use .Equals().

Upvotes: 0

Related Questions