A tiny "unconventional" code snippet



  • Earlier today, I was reviewing some recent changes to our code. It all started well, with this: 

    <font size="3">
    List<string> stringList = new List<string>();
    </font>
     

    ...but then it went downhill, when I found this:

    <font size="3">
    stringList.RemoveAll(delegate(string p1) { return (true); });
    </font>
     

    It took a little staring and head-scratching, but I eventually worked out that the confusing line above is functionally identical to:

    <font size="3">
    stringList.Clear();
    </font>

     

    Nice. 



  •  Good old predicates, I see.

     I wish the framework would let you do

    stringList.RemoveAll(value.Contains("whatever"))

     rather than having to specify the delegate.



  •  Delegates are great when used properly.

    However, most people don't seem to use them beyond event handlers



  • @Jonathan Holland said:

     Delegates are great when used properly.

    However, most people don't seem to use them beyond event handlers

    I agree.  It took me forever to even understand what a delegate was.  It took an ActionScript 3.0 app in Flash that I developed to finally teach me how they really worked.  Now I banter the term "function pointer" around like I'm some kind of pro, hehe.  What's ironic is that all the delegates used in the Flash app were for events though, but somehow something clicked and the light went on.  Maybe its just that ActionScript 3.0 has a much better event and delegate model than 2.0 did, who knows.



  • @Eric Shinn said:

     Good old predicates, I see.

     I wish the framework would let you do

    stringList.RemoveAll(value.Contains("whatever"))

     rather than having to specify the delegate.

     

    It does in the 3.0 compiler...

    For some general conditional (say a single string match) you can use RemoveAll() with a lambda expression.

    var stringList = new List<string><STRING>();
    stringList.RemoveAll(s => s == "somestring");

    And for removing say multiple matching strings you can use the extension method Except()

    var stringList = new List<string><STRING>();
    stringList.Except(new string[] { "string1", "string2", "string3" });

    Please note that some stuff regarding braces has been trimmed by the forum so the code might look slightly wrong.

    - Rob



  • <somewhat-tongue-in-cheek>

    So we have a C# programmer who doesn't know about a method in the BCL. It's fairly commonly used (at least before C# 3).

    We have another C# programmer who gets 'confused' about the basics of C#.

    You're both WTF machines, but at least there is hope in the first case.

    </somewhat-tongue-in-cheek>


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.