Monday, 18 January 2016

Func Keyword in C# with lambda expression

Q: What is Func Keyword in C#?
Ans: We could say it is a type of parameterized delegate in C#.
in this given example i am going to describe how func keyword is working with lamda expression and how we can have body of a function with return type in generic Func.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Func_Keyword
{
    class Program
    {

        public static string UpperName(string name)
        {
            return name.ToUpper();
        }

        static void Main(string[] args)
        {


            Func<string> func1 = () => "My name is Raj";
            Func<string,string> func2 = (solutation) => solutation + " Raj" ;
            Func<string, string, string> func3 = (solutation, name) => solutation + " " + name ;
         
            Console.WriteLine(func1.Invoke());
            Console.WriteLine(func2.Invoke("Mr."));
            Console.WriteLine(func3.Invoke("Mr.", "Raj"));


            func2 = UpperName;
            Console.WriteLine(func2("i was in lowercase but now uppercase"));
            Console.WriteLine(func2.Invoke("i was in lowercase but now uppercase"));


            Func<string> func4 = () =>
            {
                return "Again i am Raj";
            };
            Console.WriteLine(func4());

            Console.ReadLine();

        }

    }
}


Action<T>
The Generic Action<> delegate is defined in the System namespace of microlib.dll
This Action<> generic delegate, points to a method that takes up to 16 Parameters and returns void.

Func<T>
The generic Func<> delegate is used when we want to point to a method that returns a value.
This delegate can point to a method that takes up to 16 Parameters and returns a value.
Always remember that the final parameter of Func<> is always the return value of the method. (For examle Func< int, int, string>, this version of the Func<> delegate will take 2 int parameters and returns a string value.)