Traditional Methods
Delegates are defined as “a reference type that can be used to encapsulate a method with a specific signature” The use of delegates is involved in event handlers, callbacks, asynchronous calls and multi threading, among other uses.
Before C# 2.0, the only way to use delegates was to use named methods. In some cases, this results in forced creation of classes only for using with delegates. In some cases, these classes and methods are never even invoked directly. For example
Program
Delegates
C# 2.0 offers an elegant solution for these methods described above. Anonymous methods allow declaration of inline methods without having to define a named method. This is very useful, especially in cases where the delegated function requires short and simple code. Anonymous methods can be used anywhere where a delegate type is expected. Anonymous Method declarations consist of the keyword delegate, an optional parameter list and a statement list enclosed in parenthesis.
Program
For more on Delegates click here.
Lambda Expressions
C# 3.0 and the .NET 3.0 Runtime introduce a more powerful construct that builds on the anonymous method concept. It allows you to pass an inline expression as a delegate, with minimal syntax.
…we can do this:
The complete program is:
Program
It looks shorter and more concise, doesn’t it? But how does it work? The basic form for a lambda expression is:
In the example above, we have an argument named name, implicitly typed as string, then the lambda operator (=>), then an expression which checks to see whether name is equal to “TN”.
To understand better how the lambda expression syntax differs from the anonymous method syntax, let’s turn our example anonymous method:
We don’t need the delegate keyword, so take it out.
Let’s replace the braces with a => lambda operator to make it an inline lambda expression.
The return keyword isn’t needed because an expression is always a single line of code that returns a value. Also, remove the semicolon, because name.Equals(“TN”) is now an expression, not a full statement.
The type of the argument can be inferred as well by the compiler, so we can remove the type declaration for the argument.
And there’s our final lambda expressions.
Lambda Expressions are smart enough to infer variable types. The benefit you get with a lambada expressions you don’t get from delegates is that the compiler performs automatic type interface on the lambada arguments , so I don’t even have to mention that name above is string here.
The big advantage of lambada expression in normal coding is that syntax is more readable and less verbose. This becomes quickly more important the more complex code becomes.
For more on Lambda expression click here.
December 27, 2007 at 2:31 am
Nice one yaar…TECHNOLOGY ROCKSSSSSSSSSS