Archive for July, 2010

List<T>.BinarySearch Pitfalls

Posted in csharp on July 17, 2010 by vlipwig

The BinarySearch Method of List<T> collection can be very useful to get the zero-based index of an element.

Further more if the element you searched for is not in the List<T> you can calculate the index of the first element that is larger then the element you searched for. Just apply the ~ operator on the result of the BinarySearch:

var pos = aList.BinarySearch(aString);
if (pos < 0)
     aList.Insert(~pos, aString);

But there is one pitfall: The List<T> must already be sorted; otherwise the BinerySearch result is incorrect.
This is not a big secret. It is clearly stated in the MSDN description for the Method (under Remarks)

I saw a Bug in a Project where someone used a BinarySearch to find duplicated entries between to Lists. This works as long as the Lists are sorted. If not the result is totally nonsense.

It took a while to find this Bug.

MSDN Link:


Fun with Extension Methods

Posted in csharp on July 15, 2010 by vlipwig

In a Pair-programming session Fhad showed me some interesting ideas for extension methods.
He and his colleague used extension methods to get rid of those nasty null checking stuff:

if (object != null)
    return object.SomeProperty;
    return string.Empty;

They use a generic extension method together with a lambda expression:

public static TResult IfNotNull<T, TResult>(this T obj, Func<T, TResult> func, TResult value) where T : class
    return obj == null ? value : func(obj);

Here is an example on how to use this extension method:

SomeClass myClass;
string value = myClass.IfNotNull(obj => obj.SomeProperty, string.Empty);
//value contains string.Empty

myClass == new SomeClass();
myClass.SomeProperty = “something”;
value = myClass.IfNotNull(obj => obj.SomeProperty, string.Empty);
//value is now “something”

And here are some more extension methods I’m using:

public static bool HasItems<T>(this IList<T> list)
    return list.Count > 0;

public static bool IsEmpty<T>(this IList<T> list)
    return list.Count == 0;

Example on how to use them:

List<string> _stringList = new List<string>;

if (_stringList.HasItems()) ...
if (_stringList.IsEmpty())...

I think this code is much easier to read.

Finally a link to the msdn website about Extension Methods:
and about Lambda Expressions: