Difference between == and .Equals method in C#. Example.

The Equals() method compares only content.

Example

using System;
namespace ComparisionExample {
   class Program { 
      static void Main(string[] args) { 
         string str = "hello"; 
         string str2 = str; 
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }  
   }
}

Output

Using Equality operator: True
Using equals() method: True

The Equality operator is used to compare the reference identity.

Example

using System;
namespace Demo {
   class Program { 
      static void Main(string[] args) { 
         object str = "hello";
         char[] values = {'h','e','l','l','o'};
         object str2 = new string(values);         
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }  
   }
}

Output

Using Equality operator: False
Using equals() method: True
Share:

No comments:

Post a Comment

Tuesday, 2 July 2019

Difference between == and .Equals method in C#. Example.

The Equals() method compares only content.

Example

using System;
namespace ComparisionExample {
   class Program { 
      static void Main(string[] args) { 
         string str = "hello"; 
         string str2 = str; 
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }  
   }
}

Output

Using Equality operator: True
Using equals() method: True

The Equality operator is used to compare the reference identity.

Example

using System;
namespace Demo {
   class Program { 
      static void Main(string[] args) { 
         object str = "hello";
         char[] values = {'h','e','l','l','o'};
         object str2 = new string(values);         
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }  
   }
}

Output

Using Equality operator: False
Using equals() method: True

No comments:

Post a Comment

Popular

Total Pageviews

Archive