Never be clever

by Peter Tyrrell Monday, February 25, 2008 3:51 PM

When programming, if you don't fully understand some technique, do not use it. And don't mistake intellisense for intelligence.

Case in point.

I wanted to know whether a particular barcode was contained in a list of barcodes. If not in that list, add to another list:

string barcode = "12345";
int index = barcodeList.BinarySearch(barcode);
if (index < 0)

Ooh, binary search. Visual Studio intellisense reports:

List<T>.BinarySearch(T item): Searches the entire sorted List<T> for an element using the default comparer and returns the zero-based index of the comparer.

Sounds good to me. Sign me up!

One teary-eyed debugging session later, as barcodes are being reported NOT found that SHOULD be found, I learn the full truth from MSDN:

BinarySearch() return value is the zero-based index of item in the sorted List, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.

Oh... shazbot.

Why didn't I just use List.Contains?

string barcode = "12345";
if (!barcodeList.Contains(barcode))

Because. I am an idiot.



blog comments powered by Disqus

Month List