Hi,
This blog post summarizes the new features of C# 2.0.
Below are the new features been introduced.
§ Partial Classes
§ Static Classes
§ Generic Classes
§ Anonymous methods
§ Iterators
§ Nullable Types
Anonymous methods
- In C# 1.x, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.
- Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.
- By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
- Using anonymous methods can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when launching a new thread. See Code 2
- The local variables and parameters whose scope contain an anonymous method declaration are called Outer or Captured Variables of the anonymous method. For example, in the Code3 segment, n is an outer variable.
- Unlike local variables, the lifetime of the outer variable extends until the delegates that reference the anonymous methods are eligible for garbage collection. A reference to n is captured at the time the delegate is created.
- An anonymous method cannot access the ref or out parameters of an outer scope.
- No unsafe code can be accessed within the anonymous-method-block.
- See Code 4 –
1. Associating the delegate with an anonymous method.
2. Associating the delegate with a named method (DoWork).
- The parameter list of a delegate is compatible with an anonymous method if one of the following is true.
The anonymous method has no parameter list, and the delegate has no out parameters.
The anonymous method includes a parameter list that exactly matches the delegate’s parameters in number, types, and modifiers.
- The return type of a delegate is compatible with an anonymous method if one of the following is true.
The delegate’s return type is void, and the anonymous method has no return statements or only return statements with no expression.
The delegate’s return type is not void, and the expressions associated with all return statements in the anonymous method can be implicitly converted to the return type of the delegate.
Hope this helps
Thanks & Regards,
Arun Manglick || Senior Tech Lead
No comments:
Post a Comment