C# Programming - Strings - Discussion
Discussion Forum : Strings - General Questions (Q.No. 6)
6.
If s1 and s2 are references to two strings, then which of the following is the correct way to compare the two references?
Discussion:
5 comments Page 1 of 1.
Asd said:
9 years ago
There is no correct answer in this question :).
string s1 = "Test";
string s2 = String.Copy(s1);
Console.WriteLine(s1.Equals(s2));
Console.WriteLine(s1 == s2);
Console.WriteLine(Object.ReferenceEquals(s1, s2));
This will output:
True.
True.
False.
string s1 = "Test";
string s2 = String.Copy(s1);
Console.WriteLine(s1.Equals(s2));
Console.WriteLine(s1 == s2);
Console.WriteLine(Object.ReferenceEquals(s1, s2));
This will output:
True.
True.
False.
Max said:
1 decade ago
Using == is an incorrect way to compare two variable. For Example:
object str = "Hello";
object str1 = new string("Hello".ToCharArray());
Console.WriteLine(str == str1); // return false
Console.WriteLine(str.Equals(str1)); // return true
Reason behind this is == is used on an object whereas Equals is just a virtual method for string type it just compares the contents.
object str = "Hello";
object str1 = new string("Hello".ToCharArray());
Console.WriteLine(str == str1); // return false
Console.WriteLine(str.Equals(str1)); // return true
Reason behind this is == is used on an object whereas Equals is just a virtual method for string type it just compares the contents.
Nicholas Mahbouby said:
1 decade ago
For strings the == operator calls the static Equals(String, String) method,
Which performs an ordinal (case-sensitive and culture-insensitive) comparison.
Which performs an ordinal (case-sensitive and culture-insensitive) comparison.
Gaurav Kaushik said:
1 decade ago
s1.Equals(s2)
I think this is the best practice to compare.
Yes, s1==s2 is also a way to compare.
I think this is the best practice to compare.
Yes, s1==s2 is also a way to compare.
Satish said:
1 decade ago
s1 == s2 can also be used for string compare.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers