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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With