C# tips and tricks 30 - Difference between Equals() method and == comparison operator in c#
Вставка
- Опубліковано 6 жов 2024
- 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)+"
");
string a = "Ankpro";
string b = "Ankpro";
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b)+"
");
Student std = new Student();
std.Name = "Ankpro";
Student std1 = new Student();
std.Name = "Ankpro";
Console.WriteLine(std == std1);
Console.WriteLine(std.Equals(std1)+"
");
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)+"
");
int x = 10;
byte z = 10;
Console.WriteLine(z == x);
Console.WriteLine(z.Equals(x) + "
");
}
class Student
{
public string Name { get; set; }
}
}
}
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.
nice
Cheers! would you mind hitting *_like_* button and *_subscribe_* to our channel!
That will be awesome. We would be grateful to you. And also share this video in your circle via whatsapp, facebook and twitter.