Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents. Let’s see with some examples.
In this example we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
In this example we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
- using System;
- namespace ComparisionExample {
- class Program {
- static void Main(string[] args) {
- string name = "sandeep";
- string myName = name;
- Console.WriteLine("== operator result is {0}", name == myName);
- Console.WriteLine("Equals method result is {0}", name.Equals(myName));
- Console.ReadKey();
- }
- }
- }
No comments:
Post a Comment