String comparison question RRS feed

  • Question

  • I have business object Status with properties “ID” and “Name.


    Suppose Member is complex object with Status as a property. I check the member’s status like below


    If (Member.Status.Name  == “Active”)


    //Do something


    This code is Silverlight side, and so it will run on client machine not on the web server. (Even though this is not Silverlight forum, my question is purely C# question) I’m not sure how string comparison is done internally.

    Since this code will be running on different machines in different cultures will there be any issue in doing string comparison


    This why I got confused


    Tuesday, August 17, 2010 3:48 PM


  • The Equals method and the equality operator should always perform ordinal comparisons, while the Compare and CompareTo methods are culture sensitive (and may perform character expansion). The main problem is that it's all too easy to make assumptions based whatever culture we are using during development, so that it may be difficult to detect these problems early on; this is especially a problem when using the en-US culture, as that's what the invariant culture is based on.

    As a rule of thumb, I would suggest:

    1) Always choose those overloads that allow you to specify how characters are compared to each other and according to which culture. It might seem redundant, but it helps a lot when maintaining your application. FxCop can help you detect these issues, and it's free.

    2) Strings are not ideal to represent the status of an object. Aside of any performance consideration, the compiler cannot detect if you misspell "Active", for instance, so all you can hope for is to get a runtime error or notice some unwanted behavior (and debug). By using an enumeration, or even just a straight boolean as in:

    if (Member.Status.IsActive) {

    not only the code you write is immune from any possible localization issue: you are also letting the compiler check the spelling for you at compile time. You also get Intellisense to speed you up and (but this is a matter of personal taste) you can get more readable code.


    • Proposed as answer by Meile Zetstra Wednesday, August 18, 2010 9:42 AM
    • Marked as answer by SamAgain Tuesday, August 24, 2010 6:45 AM
    Tuesday, August 17, 2010 4:52 PM