Comparing Strings & String Case

  • Thread starter Thread starter JSheble
  • Start date Start date
J

JSheble

I realise .NET has all these great objects, specifically strings, but is it
really necessary to create a string variable (object) just to compare two
string values?

For example, I'm looking at an attribute of an XML string, and I wish to
compare it's value to a literal string, but it has to be a case in-sensitive
comparison. Do I really need to put these two values into a variable in
order to use the ToUpper() or ToLower() methods of the String object?

Heres' what I have:

if(oNode.Attributes.GetNamedItem("level").Value == "package")
{
}

or do I have to do this:

string sNodeValue = oNode.Attributes.GetNamedItem("level").Value;
string sLiteral = "package";

if( sNodeValue.ToLower() == sLiteral.ToLower() )
{
}
 
How about

String.Compare(oNode.Attributes.GetNamedItem("level").Value, "package",
true);

?
 
You can call ToLower on a literal string too:

if( sNodeValue.ToLower() == "Package".ToLower() )
{
}
 
This does a very efficient case-insensitive comparison (thanks to Jon Skeet
who pointed this out to me a few months ago):

private static System.Globalization.CompareInfo MyCompareInfo =
System.Globalization.CultureInfo.CurrentCulture.CompareInfo;

if (MyCompareInfo.Compare(String1, String2,
System.Globalization.CompareOptions.IgnoreCase) == 0)
{...}


David Anton
www.tangiblesoftwaresolutions.com
Home of the Instant C# VB.NET to C# converter
and the Instant VB C# to VB.NET converter
 
You can call ToLower on a literal string too:

if( sNodeValue.ToLower() == "Package".ToLower() )
{
}


<scratching head> Now WHY would anyone ever do such a thing?
 
Back
Top