Check if ValueTuple instances are equal in C#
Last Updated :
23 Jul, 2019
ValueTuple is a structure introduced in C# 7.0 which represents the value type Tuple. It allows you to store a data set which contains multiple values that may or may not be related to each other.
In value tuples, you can check if two value tuples are identical or not by using the ValueTuple.Equals Method. This method will return value which indicates whether the given ValueTuple instance is equal to the specified object or not. It will return true if the given tuples are equal, otherwise, return false. This method can be overloaded in two different ways:
- Equals(ValueTuple) Method
- Equals(Object) Method
Equals(ValueTuple) Method
The Equals(ValueTuple) method is used to check whether the two ValueTuple instances are equal. It always returns true. The return type of this method is System.Boolean.
Syntax:
public bool Equals (ValueTuple other);
Here, other is a value tuple to compare with the current instance.
Returns: It always returns true.
Example:
using System;
class GFG {
static public void Main()
{
var MyTple1 = ValueTuple.Create(56, 45);
var MyTple2 = ValueTuple.Create(56, 45);
bool res1 = MyTple1.Equals(MyTple2);
Console.WriteLine( "Is MyTple1 and MyTple2 equal?: " + res1);
}
}
|
Output:
Is MyTple1 and MyTple2 equal?: True
Equals(Object) Method
The Equals(Object) method is used to return a value that determines whether the current ValueTuple instance is equal to a specified object. This method will return true if the given ValueTuple instance is equal to a specified object, otherwise, it will return false.
Syntax:
public override bool Equals (object obj);
Here, obj is the object to compare to the current instance.
Return Type: The return type of this method is System.Boolean.
Example:
using System;
class GFG {
static public void Main()
{
var MyTple1 = (56);
object ob1 = 56;
bool res = MyTple1.Equals(ob1);
if (res == true )
{
Console.WriteLine( "The given object is equal to" +
" the value tuple element...!!" );
}
else
{
Console.WriteLine( "Not equal....!!" );
}
}
}
|
Output:
The given object is equal to the value tuple element...!!
Reference:
Share your thoughts in the comments
Please Login to comment...