Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Compare this instance is equal to a specified object or Int64 in C#
The Equals() method in C# is used to compare whether the current instance of a long (Int64) is equal to a specified object or another Int64 value. This method performs value-based comparison and returns a boolean result.
Syntax
Following is the syntax for the Equals() method −
public bool Equals(long value) public override bool Equals(object obj)
Parameters
-
value − A long value to compare with the current instance.
-
obj − An object to compare with the current instance.
Return Value
Returns true if the current instance equals the specified value or object; otherwise, false.
Using Equals() with Different Long Values
This example demonstrates comparing two different long values −
using System;
public class Demo {
public static void Main() {
long val1 = 150;
long val2 = 240;
Console.WriteLine("Value1 = "+val1);
Console.WriteLine("Value2 = "+val2);
Console.WriteLine("Are they equal? = "+val1.Equals(val2));
}
}
The output of the above code is −
Value1 = 150 Value2 = 240 Are they equal? = False
Using Equals() with Identical Long Values
This example demonstrates comparing two identical long values −
using System;
public class Demo {
public static void Main() {
long val1 = 8768768768;
long val2 = 8768768768;
Console.WriteLine("Value1 = "+val1);
Console.WriteLine("Value2 = "+val2);
Console.WriteLine("Are they equal? = "+val1.Equals(val2));
}
}
The output of the above code is −
Value1 = 8768768768 Value2 = 8768768768 Are they equal? = True
Using Equals() with Object Parameter
This example demonstrates comparing a long value with an object −
using System;
public class Demo {
public static void Main() {
long val1 = 500;
object obj1 = 500L;
object obj2 = "500";
Console.WriteLine("Long value: " + val1);
Console.WriteLine("Object 1 (long): " + obj1);
Console.WriteLine("Object 2 (string): " + obj2);
Console.WriteLine("val1.Equals(obj1): " + val1.Equals(obj1));
Console.WriteLine("val1.Equals(obj2): " + val1.Equals(obj2));
}
}
The output of the above code is −
Long value: 500 Object 1 (long): 500 Object 2 (string): 500 val1.Equals(obj1): True val1.Equals(obj2): False
Conclusion
The Equals() provides a reliable way to compare long values for equality. It performs type-safe comparison when used with object parameters, returning false if the object is not a long type, making it safer than using the == operator for object comparisons.
