advertisement
Anonymous Method in C# | Advanced ConceptĀ
Anonymous Methods
An anonymous method is an inline nameless block of code that can be passed as a delegate parameter.
Typically, delegates can invoke one or more named methods that are included while declaring the delegates. Before anonymous methods, to pass a small block of code to a delegate, the developer always had to create a method, and then pass it to the delegate. With the introduction of anonymous methods, the developer can pass an inline block of code to a delegate without actually creating a method.
1. Features of the anonymous method
An anonymous method is used in place of a named method if that method is to be invoked only through a delegate. An anonymous method has the following features:
- It appears as an inline code in the delegate declaration.
- It is best suited for small blocks.
- It can accept parameters of any type.
- Parameters using the ref and out keywords can be passed to it.
- It can include parameters of a generic type.
- It cannot include jump statements such as goto and break that transfer control out of the scope of the method.
2. Creating Anonymous Methods
An anonymous method is created when a delegate is instantiated or referenced with a block of unnamed code. The following points must be noted while creating anonymous methods:
- When a delegate keyword is used inside a method body, it must be followed by an anonymous method body.
- The method is defined as a set of statements within curly braces while creating an object of a delegate.
- Anonymous methods are not given any return type.
- Anonymous methods are not prefixed with access modifiers.
3. Referencing Multiple Anonymous Methods
C# allows creating and instantiating a delegate that can reference multiple anonymous methods. This is done using the += operator. The += operator is used to add additional references to either named or anonymous methods after instantiating the delegate.
4. Passing Parameters
C# allows passing parameters to anonymous methods. The type of parameters that can be passed to an anonymous method is specified at the time of declaring the delegate. These parameters are specified within parentheses. The block of code within the anonymous method can access these specified parameters just like any normal method. The parameter values can be passed to the anonymous method while invoking the delegate.
advertisement
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0