Difference between String.Equals(string1,string2) and string1.Equals(string2)

 Posted by Rajni.Shekhar on 3/16/2012 | Category: C# Interview questions | Views: 3466 | Points: 40
Answer:

If any of strings value is null, string1.Equals(string2) will throw runtime error but
String.Equals(string1,string2) will not throw any error.

Example:

string str1=null;
string str2="abc";
str2.Equals(str1); // will give runtime error
String.Equals(str1,str2); //will not give any error


Asked In: HCL Technologies | Alert Moderator 

Comments or Responses

Posted by: Naraayanan on: 4/5/2012 | Points: 10
Hi,
Welcome to DNF. you answer is right .But your Example is wrong.Please check this Code .
     try

{
string str1 = null;
string str2 = "abc";
bool chk;
chk = str1.Equals(str2); // will give runtime error
chk = String.Equals(str1, str2); //will not give any error
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Posted by: Rajni.Shekhar on: 4/6/2012 | Points: 10
Thanks Naraayanan to modify it. :)

Login to post response

More Interview Questions by Rajni.Shekhar