C# Programming - Strings - Discussion

Discussion :: 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?

[A]. s1 is s2
[B]. s1 = s2
[C]. s1 == s2
[D]. strcmp(s1, s2)
[E]. s1.Equals(s2)

Answer: Option E

Explanation:

No answer description available for this question.

Satish said: (Jan 9, 2014)  
s1 == s2 can also be used for string compare.

Gaurav Kaushik said: (Feb 3, 2014)  
s1.Equals(s2)

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

Nicholas Mahbouby said: (May 7, 2014)  
For strings the == operator calls the static Equals(String, String) method,

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

Max said: (May 12, 2014)  
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: (Jul 23, 2015)  
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.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.