C# Anonymous Methods

C# Code Snippets Anonymous Methods
Share:

About

In this code snippet, we’ll take a look at anonymous methods in C#.

Anonymous methods don’t have names(obviously). They can be defined with the delegate keyword or by using the lambda expression. They can then be put into a variable of type delegate.

Here is how to implement an anonymous method.

Code:

using System;
using System.Collections.Generic;
using System.Linq;

namespace AnonymousMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            //Examples of anonymous methods using delegate. 
            Func<string> method = delegate() { return "Hello."; };
            Console.WriteLine(method());

            Console.WriteLine("");

            //Examples of anonymous methods using the lambda expression. 
            Func<int, int, int> add = (a, b) => a + b;
            Func<int, int> sub10 = a => { return a - 10; };

            Console.WriteLine(add(10, 15));
            Console.WriteLine(sub10(15));

            Console.WriteLine("");

            //Example of a anonymous metod 
            List<int> numbers = new List<int>() { 1, 5, 8, 9 };
            
            var query = numbers.Where(n => n > 2);

            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
            
            Console.ReadLine();
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger