C# compare string ignoreCase

12,081

Solution 1

Using the Assert.AreEqual with the ignoreCase parameter is better because it doesn't require the creation of a new string (and, as pointed out by @dtb, you could work following the rules of a specific culture info)

Assert.AreEqual(user1.UserName, user2.UserName, true, CultureInfo.CurrentCulture);

Solution 2

StringInstance.ToUpperInvariant()

user1.UserName.ToUpperInvariant() == user3.UserName.ToUpperInvariant();

user3.UserName.ToUpperInvariant() == "TEST.USER";  

Solution 3

In it's simple form; you can compare two string while ignoring their case like below.

Assert.AreEqual(0,string.Compare("test", "TEST", true));

I am not sure; why you need to take the route of non culture specific case since case is a simple (non localization) unit test case. Having said that, if still you wanted to go on that direction then do refer this link.

Share:
12,081

Related videos on Youtube

user216672
Author by

user216672

A junior application developer with a lot to learn.

Updated on October 16, 2022

Comments

  • user216672
    user216672 over 1 year

    Within this test method I need to compare the strings of user3 while ignoring case sensitivity. I'm thinking I should use CultureInfo.InvariantCulture to ignoreCase. Is this the best way to accomplish this, or is there a better way?

                //set test to get user 
                AsaMembershipProvider prov = this.GetMembershipProvider();        
    
                //call get users
                MembershipUser user1 = prov.GetUser("test.user", false);
                //ask for the username with deliberate case differences
                MembershipUser user2 = prov.GetUser("TeSt.UsEr", false);
                //getting a user with Upper and lower case in the username.
                MembershipUser user3 = prov.GetUser("Test.User", false);
    
                //prove that you still get the user, 
                Assert.AreNotEqual(null, user1);
                Assert.AreNotEqual(null, user2);
    
                //test by using the “.ToLower()” function on the resulting string.
                Assert.AreEqual(user1.UserName.ToLower(), user2.UserName.ToLower());
                Assert.AreEqual(user1.UserName, "test.user");
                Assert.AreEqual(user3.UserName, "test.user");
    
  • Feidex
    Feidex almost 11 years
    Comparing strings in a case-insensitive way by converting to upper or lower case does not work in all cultures. Use string comparison methods to compare strings, not case transformations!
  • Corey Ogburn
    Corey Ogburn almost 11 years
    If it works in the culture he's using, does it make a difference?
  • user216672
    user216672 almost 11 years
    that was so much simpler than the way I was thinking I was going to have to go. Thanks!