SAF(NET) = STEPHEN A. FUQUA operating on the Web since 1995

Stephen is a web developer, Bahá'í, and interfaith activist in St. Paul, Minnesota. He likes to write about religion, social justice, sustainability, science, programming, &c.

March 4, 2009

Nice technique for modifying a subset of a List

One of my team members sent in the following piece of code, which is clearly intended to update the OrderNumber field for all objects in a List<T> of objects that match a particular productId. I took one look at it and thought "you can't do that!". But then I let the automated test run to see what happens... lo and behold, it worked. And well it should, once I thought about it.

list = cardQueue.FindAll(delegate(MyObject obj1)
{
     if (obj1.ProductId == processedProductId)
     {
         obj1.OrderNumber = orderNumber;
     }

     return true;
});

It had never occurred to me that you can modify an object inside of a Predicate<T> method. But now that I look at it, why not? After all, in C#, objects are passed around by reference, not value –when the method tests obj1 to see if its ProductId value is the one we are searching for, then that is the “real” object, not just a copy. Thus the real object can be modified.

deprecated

On safnet.com

Other sites managed or developed by S.A.F.

S.A.F. elsewhere on the web

  • LinkedIn
    LinkedIn can actually be useful when looking for prospective hires and business or organizational partners
  • GoodReads
    A fun and relatively-unknown social networking site geared towards one's book list
  • Live Journal
    Mirror of the blog at safnet.com, so that a few LJ friends can more easily read and comment there