Find the Bug - 3

Continuing with the series of Find the Bug, another simple question this time. A developer is asked to write a function which compares the two strings and and return true if two strings are same and false otherwise, developer ends up writing the following code:
public static bool Compare(string str1,string str2)
{
try
{
int size = str1.Length;
for (int i = 0; i < size; i++)
{
if (str1[i] != str2[i])
return false;
}
return true;
}
catch (IndexOutOfRangeException ex)
{
return false;
}
}
Under what all test cases this code will either fail are give wrong results.

3 comments:

  1. When either of the strings are null, or if second string is longer than the first.

    ReplyDelete
  2. Shuchita4:56 PM

    In case either of the strings contain leading or trailing whitespace.

    ReplyDelete
  3. Anonymous5:34 PM

    Hi,
    If the first string is null and second is not null it will return true.
    If the first string is "apple" and the second string is "applessss" then also it will return true.

    ReplyDelete