Thursday, August 27, 2009

Walk Of Shame.

So today as I am looking into why a program failed. I ran across a wonderful little bug that was completely my fault. The offending line of code is.

   76 this._AviableCabinets.RemoveAt(this._AviableCabinets.FindIndex(c => c.Name == LanguageDB.GetText("SelectDestLocalAllCabinetsText")));

The error it will throw is index out of bounds.

The solution is easy.

   76 var cLoc = this._AviableCabinets.FindIndex(c => c.Name == LanguageDB.GetText("SelectDestLocalAllCabinetsText"));
   77             if (cLoc > -1)
   78             {
   79                 this._AviableCabinets.RemoveAt(cLoc);
   80             }


Some Times it is better to not do it all on one line.

2 comments:

Mel said...

Actually, why remove it by index when you can just remove it by object, like so:

this._AviableCabinets.Remove(this._AviableCabinets.Find(c => c.Name == LanguageDB.GetText("SelectDestLocalAllCabinetsText")));

The Remove() doesn't have any problems if you pass it null, which is what the Find function will return if the object wasn't found.

Much simpler and probably quicker than using indexes. Assuming '_AviableCabinets' is a List<T> that is.

Erin said...

He he. You know where that code came from right, and who wrote the first version of it.