Wednesday 8 May 2013

What is Action,Func delegate in C#

Action: 

Encapsulates a method that has no parameter or one parameter or more parameters and does not return a value, method return type should be void(c#) or Sub .... End Sub (vb.net).

E.g.

    class Program
    {


        static void Main(string[] args)
        {
            Action<int> action = new Action<int>(DoSomething);
            action.Invoke(1009);
        }

        static void DoSomething(int i)
        {
            Console.WriteLine(i);
        } 
    }

O/P:
1009

Func:

Encapsulates a method that has no parameters or one or parameters and returns a value of the type specified by the TResult parameter.

//Func delegate with one parameter and TResult

public delegate TResult Func<in T, out TResult>(T arg)

E.g.
   class Program
    {
        private static void Main(string[] args)
        {            
            Func<int, double> func = new Func<int, double>(CalcualteSomething);
            Console.WriteLine(func(5)); //Should Print 25
        }
  
        private static double CalcualteSomething(int i)
        {      
           return (double) i*2;
        }
    } 


No comments:

Post a Comment

Custome Service Class to connect wcf service

  using  System; using  System.ServiceModel; namespace Custom.Service.Client {      // Borrowed from: http://old.iserviceoriented.com/blog/p...