Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison of typed objects in generic class [duplicate]

Tags:

c#

types

generics

Following code is given, i want to just compare two objects inside a generic class.

public bool Compare<T>()
    {
        T var1 = default(T);
        T var2 = default(T);        
        return var1 == var2;
        //Error CS0019  Operator '==' cannot be applied to operands of type 'T' and 'T'
    }

Can anybody explain why it is not possible to compare these two objects in this generic class?

like image 218
Teimo Avatar asked Apr 06 '16 11:04

Teimo


People also ask

How can I compare two generic types in Java?

Best solution that i came up with is to add a Comparator to the argument of sorting function and use the compare method. You will have to override the compare(T o1,To2) method at/before function call while creating new Comparator<T>() , T to be replaced by the desired type.

How do I compare generic types in C#?

To enable two objects of a generic type parameter to be compared, they must implement the IComparable or IComparable<T>, and/or IEquatable<T> interfaces. Both versions of IComparable define the CompareTo() method and IEquatable<T> defines the Equals() method.

Can a generic can take any object data type?

Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type.

Can generic methods be static?

Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.


1 Answers

The Type T is not necessarily a reference type, T is a type argument and can be a class or a struct, so the compiler will not be able to make that assumption.

You can do like

public bool Compare<T>()
{           
        T var1 = default(T);
        T var2 = default(T);

        return !EqualityComparer<T>.Default.Equals(var1, var2);
}

You can also try to make T IComparable<T> or else you can try to use an IComparer<T> to your class.

like image 71
Rahul Tripathi Avatar answered Oct 01 '22 08:10

Rahul Tripathi