Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The spirit of your code is correct but I think you'll get a runtime error since the inferred type of your iteration variable, foo, will be System.Object.

Here's a slightly more idiomatic C# 2.0 (i.e. sans var goodness)

  ArrayList descriptions = new ArrayList(mylist.Length);
  
   foreach (Foo foo in myList)
    if (foo.Description != "")
        descriptions.Add(foo.Description);
  
  return String.Join("\n", descriptions);


Hey, you're right, it would be a compile time error but indeed. I'd rather supply a generic constraint <Foo> to ArrayList than have it be cast to Foo that way (does it even do that automatically?).

Also, do you think leaving out the braces is idiomatic? I think it looks really pretty but I don't like it at all, it is too brittle.


Eliding the braces does make it a bit less idiomatic I suppose; but in ten years of programming I don't think I've ever been bitten by a bug caused by that style... not even in JavaScript.

On the other hand, I think the risk of making the code slightly more brittle is worth it if it makes it much more pleasant to read. Whenever I see a for/foreach followed by a single statement then I know that the code is doing a simple projection (i.e. Select in Linq or SQL parlance). If it’s a for/foreach followed by an if statement followed by some other statement (as in the above code) then I know it’s a simple filter and projection (i.e. Where and Select).

But I wanted to illustrate your larger point, which is that C# programmers shouldn’t be so quick to use functional idioms since imperative code can not only look just a pretty, but it’s almost always slightly more performant since it doesn’t imply as many allocations and indirections.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: