C# – Dynamic methods with lambda expressions

 

 

Lambda expression is a function that is not bound with an identifier

The logic behind this is like the one shown below.

(parameters) => expression

I know it looks weird so I will try to make it look less weirdo.

using System;

namespace lambdaexpressions
{
    public class Program
    {
        
        public static void Main(string[] args)
        {
            
			Action greetings = () => { Console.WriteLine("Hi, Sir! Welcome."); };
 			greetings();

  			Action saymyname = (name) => { Console.WriteLine("Hi "+name+"! Have a nice day!" ); };
			saymyname("John Doe");
			saymyname("Jane Doe");
			saymyname("Mehmet Burak");
  			
            
        }
        
    }
}

Here, Lambda expressions let us use dynamic functions.

Output:

Hi, Sir! Welcome.
Hi John Doe! Have a nice day!
Hi Jane Doe! Have a nice day!
Hi Mehmet Burak! Have a nice day!
using System;

namespace lambdaexpressions
{
    public class Program
    {
		static void nameandsurname(Action callback,string surname){
		
			Console.Write("Hi, ");
			callback();
			Console.WriteLine(surname + "! How are ye?");
			
		}
		
        public static void Main(string[] args)
        {
            string gender = "male";
	    nameandsurname( () => { if(gender =="male"){ Console.Write("John "); }else if(gender =="female"){	Console.Write("Jane ");	}},"Doe");
        }
    }
}

In here, we used System.Action to redirect the parameters to our function.
Output:

Hi, John Doe! How are ye?

Leave a Reply

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