Using comparison operators such as'! = 'AND' == ', with generics limited as a value in C #

I have the following code:

class Foo<T> where T : struct { private T t; [...] public bool Equals(T t) { return this.t == t; } } 

When I try to compile, it causes the following error:

The operator '==' cannot be applied to operands of type 'T' and 'T'

Why can't this be done? If the restriction was where T : class , this would work. But I need it to be a value type, because in my implementation this generic will always be an enumeration.

What am I doing to get around this, use the Object.Equals() method. Will this ensure correct behavior all the time since I am only comparing T?

+4
source share
2 answers

This is an unpopular limitation of the constraint system. You cannot restrict the type of value in accordance with specific operations on it, if they are not defined in the interface. Thus, you cannot restrict the definitions of statements, since they will not be defined for all types of values, and the restriction struct allows you to pass any type of value.

 struct A { } 

This is not defined == , and yet your restriction says that you would be happy to accept it. Therefore, you cannot use == .

The reason it differs from reference types is because the definition == (identity comparison) is available to them.

The == implementation on enum is close enough to the Equals implementation that your workaround is ok.

Compare with the situation for > with numeric types! There is no such workaround. Standard numbers do not have an interface with methods such as GreaterThan , etc.

+3
source

Check out this article by John Skeet and Mark Gravell. It describes the implementation of "generic operators" using Linq expressions. The actual implementation is available in the MiscUtil library

+1
source

Source: https://habr.com/ru/post/1303105/


All Articles