Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Omer van Kloeten's Facebook profile

Get Firefox

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

Lambda Expressions, Anonymous Methods and Methods

I really think Krzysztof and friends should post some guidelines in the spirit of The Framework Design Guidelines (read: The Book You Must Read) for lambda expressions, anonymous methods and methods, so there won't be any mixup as to what should be used. I'd hate to see people start writing long anonymous method in the middle of their code - they really disturb the flow.

My suggestion:
  • Do use a lambda expression if it consists of only one expression. This is what they're there for.
  • Avoid using a lambda expression if the types of parameters and return value are not obvious.
  • Do use an anonymous method if it consists of between 1 and 4 lines of code.
  • Consider a method instead if an anonymous method if it looks unreadable in the context of the code around it.
  • Do Not use an anonymous method if the code contained in it needs to be re-used.
And also:
  • Do match the names of parameters from the delegate's declaration when declaring them in a lambda expression or an anonymous method.
Again, this is my opinion and the principles I try to follow in my code. I'd love to hear your ideas too.

I'd also love to see a refactoring feature in Orcas that lets you refactor between lambda expressions, anonymous methods and methods.

Comments

Jordan T said:

Keep in mind that the Framework Design Guideline book only addresses public API's. I don't know that the use of lambdas could be included in a public API signature.
# July 10, 2006 7:43 AM

Omer van Kloeten said:

Yeah, you're right.

They really should place it somewhere, though. Maybe FxCop is the address for this.

# July 10, 2006 11:43 AM

gozh2002 said:

sorry, lambda expression has not come yet, it is on 3.0 right? I also wondering if the framework design guideline book has already updated with a 2.0 version?
# July 11, 2006 10:21 PM

Omer van Kloeten said:

Yes, they're not here yet, but rather they are an extension to C# 2.0.

The FDG has some 2.0 content, but if I remember correctly, only information about designing with generic classes from the BCL.

# July 11, 2006 11:56 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)