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?
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.
( 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.
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.
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.
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
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