C# Programming - Strings - Discussion

Discussion Forum : Strings - General Questions (Q.No. 6)
If s1 and s2 are references to two strings, then which of the following is the correct way to compare the two references?
s1 is s2
s1 = s2
s1 == s2
strcmp(s1, s2)
Answer: Option
No answer description is available. Let's discuss.
5 comments Page 1 of 1.

Satish said:   10 years ago
s1 == s2 can also be used for string compare.

Gaurav Kaushik said:   10 years ago

I think this is the best practice to compare.
Yes, s1==s2 is also a way to compare.

Nicholas Mahbouby said:   10 years ago
For strings the == operator calls the static Equals(String, String) method,

Which performs an ordinal (case-sensitive and culture-insensitive) comparison.

Max said:   10 years 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.

Asd said:   8 years ago
There is no correct answer in this question :).

string s1 = "Test";
string s2 = String.Copy(s1);
Console.WriteLine(s1 == s2);
Console.WriteLine(Object.ReferenceEquals(s1, s2));

This will output:


Post your comments here:

Your comments will be displayed after verification.