Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Are 2 'English United States' Strings Equal?

I am tired of writing (and seeing) code that looks like this in our application:

If myString.Trim().ToUpper = "O"

or something like this:

If String.Compare(myString, "O", True, New System.Globalization.CultureInfo("en-US") = 0

So, I wrote a 1 line utility method:

Public Function StringsAreEqual(ByVal string1 As String, _

ByVal string2 As String) _

As Boolean

Return String.Compare(string1, string2, True, New System.Globalization.CultureInfo("en-US")) = 0

End Function ' StringsAreEqual

 

6 Comments

  • Explictly setting the culture like that seems risky.

  • I agree with monsoondawn. Risky.



    But I do agree with your implemenation, especially since the original has to create a new string object because of the ToUpper. The String.Compare doesn't create anything new. That ToUpper() is actually something FxCop will catch because it recognizes in the the IL that a new string object was created simply for equality, and there is a better way to do it, like you did with String.Compare.

  • Why don't you use the InvariantCulture, since that is essentially the same as US, doesn't change and doesn't cause any allocations.

  • The app will always be 100% United States English. I am ok with explicitly setting the culture. On the column question, String.Compare will excepet a Null and the signature to my method does require 2 Strings.


  • Shouldn't your utility method be static? I.e. marked up as Shared in VB.NET? Looks like it's an instance method at the moment.



    Just wondering. ;)

  • Resides in a Module



    "Public Module Tools"

Comments have been disabled for this content.