Through this blog I will show you the tricks
to compare the string in C#.
Usually, When people compare the two strings (Don't know whether, if they are in
upper case or lower case), they do it like this..
string
FirstString = "GAURAV";
string SecondString =
"gaurav";
if
(FirstString .ToUpper() == SecondString.ToUpper())
{
Response.Write("true");
}
Comparing the two string using the above code will increase the additional
memory allocation overhead on the compiler.
The above task can be accomplish by avoiding string allocation overhead like
this.
string
FirstString = "GAURAV";
string SecondString =
"gaurav";
if (FirstString.Equals(SecondString,
StringComparison.OrdinalIgnoreCase))
{
Response.Write("Matched");
}
In the above
code,StringComparison.OrdinalIgnoreCase will lead to compare the string by
ignoring it's case.
So, Now your code to compare the two strings:
if
(FirstString .ToUpper() == SecondString.ToUpper())
{
Response.Write("true");
}
will be replace as
if (FirstString.Equals(SecondString,
StringComparison.OrdinalIgnoreCase))
{
Response.Write("Matched");
}
This could also be quite null-safe to compare string with null
values.
Just like.
string
FirstString = null;
string SecondString = "gaurav";
var
Matched = String.Equals(FirstString,
SecondString, StringComparison.OrdinalIgnoreCase);
if
(Matched)
{
Response.Write("true");
}
else
{
Response.Write("false");
}