Why does my comparison always return false?

I have a group of usernames in this arraylist and I want to check if the username exists in arraylist or not, but the method always returns false.

public bool check_username(ArrayList userList, string username) { for (int i = 0; i < userList.Count; i++) { if (userList[i].ToString() == username) { return true; } } return false; } 
0
c #
source share
3 answers

Without looking at your list or what you are going through, we cannot know for sure, but it could be a normalization problem.

Bob, bob, bob, bob, etc. do not match when comparing strings.

Replace the if statement with the following:

 if(userList[i].ToString().ToLower() == username.ToLower()) { return true; } 
+1
source share

Consider your string comparison case insensitive.

 username.Equals(userList[i].ToString(), StringComparison.OrdinalIgnoreCase); 

Or, if all the elements in your ArrayList user list are strings, and you are using .NET 3.5 or later, you can simplify this with LINQ:

 public bool check_username(ArrayList userList, string username) { return userList.Cast<string>() .Any(s => s.Equals(username, StringComparison.OrdinalIgnoreCase); } 
+4
source share

There are several reasons why I might think that it might make this function always return false.

  • Are you sure that your userList and username will always have the same enclosure? It would be good practice to use .ToLower () or .ToUpper () to make sure that the case matches if you are not going to have the case be part of the match.

  • Are you sure there are no extra spaces in any line? It is recommended that you use .Trim () when you are comparing strings where there may be extra spaces.

  • Using the .Equals () method when comparing a string is more reliable than the boolean operator ==. Sometimes a logical operator produces incorrect results.

  • Are you sure you should get the true result? Is it possible that one line contains a hidden character that you are not aware of? Use a debugger to check string values.

+1
source share

All Articles