The concept of anonymous method was introduced in C# 2.0. An anonymous method is inline unnamed method in the code. It is created using the delegate keyword and doesn’t required name and return type. Hence we can say, an anonymous method has only body without name, optional parameters and return type. An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.
Features of anonymous method
- A variable, declared outside the anonymous method can be accessed inside the anonymous method.
- A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.
- We use anonymous method in event handling.
- An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
- Unsafe code can’t be accessed within an anonymous method.
- An anonymous method can’t access the ref or out parameters of an outer scope.