Comparing Strings & String Case

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() )
{
}
 
B

Bruce Wood

How about

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

?
 
C

Chris Dunaway

You can call ToLower on a literal string too:

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

Guest

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
 
G

goody8

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top