public static IEnumerable<T> Method<T>(IEnumerable<T> iterable){
T previous = default(T);
foreach(T current in iterable){
if (!current.Equals(previous)){
previous = current;
yield return current;
}
}
}
I don't have any questions about this code, but just why if it is possible to compare two objects of type T using:
if (!current.Equals(previous))
Then why is it not possible to compare using:
if (!current == previous)
The ! gives you an error saying
Operator '!' cannot be applied to operand of type 'T'
And if you remove that you get:
Operator '==' cannot be applied to operands of type 'T' and 'T'
I gave up on a code challenge because it seemed to be telling me you literally can't compare one T to another. Then I found out you can do that but just with different syntax/using a specific method.
Can anyone advise why this would be please?
See this section of the language specification where
==is specified. You can see that the language only has these overloads of==predefined:The type parameter
Tin your method is not constrained to anything, so what if it is, for example, a struct type? As you can see from the above list, there are no==operators defined for an arbitrary struct type.If you add a
T: classconstraint, then you would be able to use==on it, because there is a==operator for all classes.On the other hand, there is an
Equalsmethod declared inSystem.Object, from which every type in C# inherits from. Therefore, it is possible to useEqualson values of typeT, even whenTcan be any type.