C# code for string comparision

//string comaparision


string strval1 = "shivu";
string strval2 = "SHIVU";


//dont use this like this code, bec here two instences of string will created
//at the time of ToUpper method

if (strval1.ToUpper().Equals(strval2.ToUpper()))
Trace.Write("matching");
else
Trace.Write("not matching");


//Put this code instead of above code.

if (strval1.Equals(strval2, StringComparison.InvariantCultureIgnoreCase))
Trace.Write("matching");
else
Trace.Write("not matching");


Comments

Author: Umesh Bhosale03 Apr 2014 Member Level: Silver   Points : 0

Hello
it is good habit to either check with toUpper() or toLower().
and you must Trim() a string before it is process.

Thanks
Umesh Bhosale

Author: Shivashankar Chincholi05 Aug 2014 Member Level: Gold   Points : 0

Two more strings objects created in memory when you use ToUpper() or ToLower() methods while comparing. Instead use StringComparison.InvariantCultureIgnoreCase to avoid that.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: