C# tips and tricks 30 – Difference between Equals() method and == comparison operator in c#

2
2



What is “==“ ?

The == is a comparison operator.
The == Operator compares the reference identity.
You can compare any primitive type such as int, char, float and Booleans.
The == operator returns a boolean value.
When used with objects, the == operator compares the two object references and determines whether they refer to the same instance.

What is Equals() ?
The Equals() method compares only the contents.
Equals() is a method available in the String class that is used to compare two strings and determine whether they are equal.
The Equals() returns a boolean value.

Code sample :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EqualentDemo
{
class Program
{
static void Main(string[] args)
{
int i = 10;
int y = 10;
Console.WriteLine(i==y);
Console.WriteLine(i.Equals(y)+”n”);

string a = “Ankpro”;
string b = “Ankpro”;
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b)+”n”);

Student std = new Student();
std.Name = “Ankpro”;
Student std1 = new Student();
std.Name = “Ankpro”;
Console.WriteLine(std == std1);
Console.WriteLine(std.Equals(std1)+”n”);

object str = new string(new char[] { ‘A’, ‘N’, ‘K’, ‘P’, ‘R’, ‘O’ });
object str1 = new string(new char[] { ‘A’, ‘N’, ‘K’, ‘P’, ‘R’, ‘O’ });
Console.WriteLine(str == str1);
Console.WriteLine(str.Equals(str1)+”n”);

int x = 10;
byte z = 10;
Console.WriteLine(z == x);
Console.WriteLine(z.Equals(x) + “n”);

}

class Student
{
public string Name { get; set; }
}
}
}

Nguồn:https://wijstaanvooronzegrondrechten.org/

2 COMMENTS

  1. Bro good video but you missed 2 things. 1. For the class object you have not assigned a value for std1 variable. 2. you have not explained why the comparison values are different for the last 2 sections.

LEAVE A REPLY

Please enter your comment!
Please enter your name here