Anonymous Method with C#
Satya Prakash Chhikara
.NET 8 | .NET Core | ASP.NET | MVC | Software Development | Mobile Development | Web Development | ERP | CMS | Microsoft Technologies | AI Automation | DevOps | AWS | Azure
Anonymous Method
As name suggests, anonymous method is a function without having a name. You can say code block with a name, and this can be assigned to a variable of delegate type and defined as delegate.
Before understanding anonymous methods, we need to understand delegate first. Let’s consider below example
?
?
?
To work with delegates, we followed the steps below.
1.????? Declare delegate with parameters
2.????? Implement method which need to be pointed from delegate
3.????? Create delegate object and pass method name in constructor of delegate and invoke method.
?
Above example, you saw that we are passing/binding function to delegate “PrintHello”, we can also bind a code block to a delegate.
In the above code, you can see that we have written an in-line code block which needs to be executed once delegate will be invoked. In this case, as you can see, instead of a method, we are binding the delegate to an unnamed code block which is also called an anonymous method and in C#, the anonymous methods are created by using the delegate keyword and if the anonymous method requires any input parameter, then you can pass the parameter within the parenthesis.?
?
Let’s look at another example of anonymous method. Suppose we have a list of employees, and we need to find if employee exist into database.
We can implement this using below code
?
?
In the above example, you can see we have first implement method, IsEmployeeExist, then we define Predicate generic delegate type and we pass method name.
?
We can achieve this using anonymous method using just one line of code
?
?
?
?
?