Looking in Func Delegates

This is an extension of my earlier blog post. I myself, find delegates as one of  the most powerful type to use in C#. It helps in writing very flexible and scalable program.

As I already discussed in my last blog that in the traditional way, we need to write more code.There I also discussed, One predefined delegate Action delegate that is provided by the framework.There are four flavors of Action delegate is provided.

One more type of predefined delegate that is provided by .NET that is counterpart Action delegate  . As we saw that it always returns void. But Func returns a value instead of void as Action does.

There is also 5 flavours of the Func delegate is provided.These are

- Public delegate TResult Func<TResult>()

– Public delegate TResult Func<TResult>()  // Take no parameter and returns a value

-  Public delegate TResult Func<T, TResult>(T t)  // Take one input parameter and returns a value

- Public delegate TResult Func<T1, T2, TResult>(T1 t1, T2 t2)  // Take 2 input parameter and returns a value

- Public delegate TResult Func<T1, T2, T3, TResult>(T1 t1, T2 t2, T3 t3)  // Take 3 input parameter and returns a value

- Public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 t1, T2 t2, T3 t3,T4 t4)  // Take 4 input parameter and returns a value

If we see the declaration, TResult is put at last, this is just a convention. One can put it wherever s/he wants.

First lets see first one , with no parameter and returning a value

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable and assigning it a function
Func<string> myFunc = SayHello;

//Calling function using Func Delegate
string returnedString = myFunc();

Console.WriteLine(returnedString);

Console.ReadKey();
}

private static string SayHello()
{
return "Hello Dude!!";
}
}

Now lets move to code to another overload of Func Delegate. It takes two input parameter and resturns a value.

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes two input parameters and returns a value) and assigning it a function
Func<double, double, double> myFunc1 = Add;

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5);

Console.WriteLine(sum);

Console.ReadKey();
}

private static double Add(double first, double second)
{
return first + second;
}
}

It is also same as Action delegate. i e It can also be used with Anonymous functions and Lambda functions. Lets have a quick look on both

Anonymous Function:

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes three input parameters and returns a value) and assigning it an Anonyomus function
Func<double, double, double, double> myFunc1 = delegate(double d1, double d2, double d3)
{
return d1 + d2 + d3;
};

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5, 5.5);

Console.WriteLine(sum);

Console.ReadKey();
}
}

Lambda Function:

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
static void Main(string[] args)
{

Func<Employee,string> checkEmployee = s=>{
if (s.Id > 11)
return s.Name;
else
return "Employee is not with the given Criteria.";
};

Console.WriteLine(checkEmployee(new Employee() {Id=12, Name="Brij"}));
Console.WriteLine(checkEmployee(new Employee() {Id=10, Name="Abhijit"}));

Console.ReadKey();
}
}

Hope you all must have enjoyed the delegates.

We use delegates a lot. But most of us, use the traditional way in programs. When I learnt first these Action and Func delegates few weeks back, I found it very useful. It helps us writing better and well organised code, also less error prone code. I talked to lot of developers, they didn’t have any idea about these predefined delegates. So I thought of sharing to you all.

Please share your valuable feedback.

Cheers,

Brij

Exploring Action Delegate

We used delegate a lot in some or other way. Like as we know, the event base model that we use in windows as web programming, is based on delegate only. I am in the habit of using delegates often. In last few days, I found a very elegent way to use the delegate.I was in the habit of of using only generic delegates that allows us type safety and lot more flexibility.

In our traditional programming, we use the delegate as in the following steps.

  1. Declaring the delegate
  2. Creating object of the delegate and assigning it to appropriate function
  3. Calling the delegate

Lets see the code

 public class Program
    {
        //Declaring an delegate
        public delegate void MyDelegate<R, S>(R r, S s);
        public static void Main(string[] args)
        {
            //Creating an Action variable and assigning it to a function
            MyDelegate<int, int> m1 = Multiply;
            //Calling the method
            m1(3, 4);
            Console.ReadKey();
        }

        public static void Multiply(int i, int j)
        {
            Console.WriteLine(i * j);
        }
    }

.NET 2.0 introcuced one generic delegate Action which takes a single parameter and returns nothing. Its declaration is
-Public delegate void Action<T1>(T1 t1) // Takes 1 parameter and returns nothing
This is a very much elegatent way to use the delegate.

And C# 3.0, introduced 4 delegates which are as

  1. Public delegate void Action() // Takes no parameter and returns nothing
  2. Public delegate void Action<T1,T2>(T1 t1,T2 t2) // Takes 2 parameters and returns nothing
  3. Public delegate void Action<T1,T2,T3>(T1 t1,T2 t2,T3 t3) // Takes 3 parameters and returns nothing
  4. Public delegate void Action<T1,T2,T3,T4>(T1 t1,T2 t2,T3 t3),T4 t4) // Takes 4 parameters and returns nothing

Lets see them running

public class Program
{
public static void Main(string[] args)
{
//Creating an Action variable and assigning it to a function
Action myAction = Multiply;
//Calling the method
myAction(3, 4);

//Also can be called as
myAction.Invoke(3, 4);
}

public static void Multiply(int i,int j)
{
Console.WriteLine(i * j);
}
}

As from the code, we can also see that Action delegate also provide a method invoke to call the method.

These Action delegate also can be used with Anonymous Methods as

public class Program
{
public static void Main(string[] args)
{
//Creating an Action variable and assigning it to a function
Action myAction = delegate(int i, int j) { Console.WriteLine(i * j); };
//Calling the method
myAction(3, 4);

Console.ReadKey();
}
}

Also can be used with lambda function. Lets see

public class Program
    {
        public static void Main(string[] args)
        {
            //Creating an Action variable and assigning it to a function
            Action<int> myAction = s => Console.WriteLine(s * 5);
            //Calling the method
            myAction(3);

            Console.ReadKey();
        }
    }

So code delegently and efficiently.

Note: The ForEach and ForEach<T> methods each take an Action<T> delegate as a parameter. The method encapsulated by the delegate allows us to perform an action on each element in the array or list.

Happy .Neting….

Cheers,
Brij