Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to check value tuples for equality in C#?

Given two variables of type (int, int), how do I check if they represent equal values?

For example:

var a = (1, 2);
var b = (1, 2);

var c = a == b; // Error CS0019 Operator '==' cannot be applied to operands
                // of type '(int, int)' and '(int, int)'

How is this comparison meant to be done in C# 7? Should I use .Equals instead or do it some other way?

like image 733
Ivan Avatar asked May 26 '17 04:05

Ivan


People also ask

How do you check for equality in C and C++?

Checking for equality in C and C++. identifier == identifier; The == sign is used to compare primitive types such as char, int, float, etc. The comparison operator returns true if the two identifiers are equal.

Is it possible to use == in a value tuple?

( For details of how Equals () works, check out the source .) As of C# 7.3, direct support for == has been added to value tuples: Note that == here is not an operator defined by the tuple types.

Is there a way to use == operator in a tuple?

As of C# 7.3, direct support for == has been added to value tuples: Note that == here is not an operator defined by the tuple types. It's a "compiler trick" that recursively (for nested tuples) performs == on each of the elements. As a result, this technique can only be used if the elements support == themselves.

How to use memcmp to compare structs for equality?

You can't use memcmp to compare structs for equality due to potential random padding characters between field in structs. You have to use member-wise comparison to be safe. Show activity on this post. @Greg is correct that one must write explicit comparison functions in the general case.


1 Answers

Prior to C# 7.3, you had two choices: use .Equals, or you can write out the == comparison long-hand, for elements that themselves support ==:

(a, b).Equals((c, d)) // true if a.Equals(c) && b.Equals(d)

a == c && b == d // works if the types support ==

(For details of how Equals() works, check out the source.)

As of C# 7.3, direct support for == has been added to value tuples:

(a, b) == (c, d) // compiler converts to a == c && b == d

Note that == here is not an operator defined by the tuple types. It's a "compiler trick" that recursively (for nested tuples) performs == on each of the elements. As a result, this technique can only be used if the elements support == themselves. As a result, this approach does not work for generics, unless constrained to types that do support ==. So the following code will not compile:

public bool Compare<T1, T2>((T1 a, T2 b) x, (T1 a, T2 b) y) => x == y
like image 64
David Arno Avatar answered Oct 09 '22 12:10

David Arno