Caveman's Blog

My commitment to learning.

Dotnet: String comparison

leave a comment »

I know that this might look like a trivial post, but read on to find some cool stuff about string compare. Following is the typical style of implementing string comparison in C#. I have recently realized that a new string object is created during the conversion to Upper case and that new object has to be garbage collected later.

            string str = "Hello";
            if (str.ToUpper().Equals("HELLO"))
                Console.WriteLine("Strings are same");

Instead of converting the string to upper case or lower case, we can use an overloaded equals method that makes string comparison more efficient. This overloaded method take an additional argument of StringComparision type and that can be used, like in the code below:

            string str = "Hello";
            if (str.Equals("HELLO", StringComparison.InvariantCultureIgnoreCase))
                Console.WriteLine("Strings are same");

In the example above, when the value of str is null, a null reference exception will be thrown. In such a case, the static compare method of the String class can be employed to handle this situation gracefully, like in the following code snippet:

            string str = null;
            if (String.Compare(str, "HELLO", true) == 0)
                Console.WriteLine("Strings are same");

Written by cavemansblog

May 3, 2011 at 10:25 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: