Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# compare string ignoreCase

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");
like image 471
user216672 Avatar asked May 09 '13 21:05

user216672


2 Answers

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);
like image 58
Steve Avatar answered Nov 13 '22 05:11

Steve


StringInstance.ToUpperInvariant()

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

user3.UserName.ToUpperInvariant() == "TEST.USER";  
like image 26
Daniel Möller Avatar answered Nov 13 '22 06:11

Daniel Möller