Quiz: Searching in a managed array

Sorry for my recent lack of blogging.  There's been a lot going on these days!

As the banner on my blog now indicates, you'll be able to catch me at two upcoming conferences.  As with TechEd in June, Sonja Keserovic and I will be giving an Interop presentation at this year's PDC in October.  This presentation will be brand new, though.  Feel free to make suggestions if you're dying to hear about certain topics!  One month before that, I'll be giving two presentations at WinSummit in Switzerland - one on PInvoke, and one on COM Interoperability.  Hopefully I'll see you there!

Yesterday I learned about something that surprised me.  Maybe it won't surprise you, but I'm going to share it anyway.  If it prevents just one person from introducing a subtle bug in their code, then it was worth it!

If you're writing managed code and you need to efficiently find elements in an array, you'll be happy to know that you don't have to write your own binary search algorithm.  System.Array has a static BinarySearch method!  (System.Collections.ArrayList has an instance BinarySearch method, too.)

So what's wrong with the following C# code?  Why does it print "Not found! "?

    // WARNING: This code has a bug!
int [] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int index = Array.BinarySearch(numbers, 3);

    if (index < 0)
Console.WriteLine("Not found!");
else
Console.WriteLine("Found at index " + index);