Thursday 25 April 2013

Func delegate


The Func and Action delegates are a set of generic delegates that can work for methods of any return type
(for Func) and reasonable number of arguments. These delegates are defined in the System namespace. The
Action represents any function that may accept up to 16 parameters and returns void, for example,
Action<T1>, where T1 refers to the input parameters and can be of any data type. Func is the same as Action
but it has a return value of any type, for example, Func<T1, TResult> where T1 input parameters can be of

any type and TResult is a returned value of any type. The only difference between Action and Func is the
return value. In the following sections, we will explore more about Func


Func

The Func class is used to encapsulate method information in C#. The Func class is defined in the mscorlib.
dll (C:\Windows\Microsoft.NET\ Framework\v4.0.30319),



The signature of the Func<TResult> class is shown in Listing 1-1

Listing 1-1. Signature of the Func<TResult>

.class public auto ansi sealed Func<+ TResult> extends System.MulticastDelegate

The Func class declaration is shown in Listing 1-2.
Listing 1-2. Func Class Definition in IL Format
.class public auto ansi sealed Func<+ TResult> extends System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname instance void
.ctor(object 'object', native int 'method') runtime managed
{}
.method public hidebysig newslot virtual instance class System.IAsyncResult
BeginInvoke(class System.AsyncCallback callback, object 'object') runtime managed
{}
.method public hidebysig newslot virtual instance !TResult
EndInvoke(class System.IAsyncResult result) runtime managed
{}
.method public hidebysig newslot virtual instance !TResult

Invoke() runtime managed

{}
}

Func<TResult> is a generic type, which inherits from the MulticastDelegate class and later inherits
from the delegate class.

 Func and Delegate relationship
The Func<TResult> class will have all the functionality and properties of the MulticastDelegate and
Delegate types due to the inherent relationship between Func<TResult> and MulticastDelegate and the
Delegate classes. The Func class has BeginInvoke, EndInvoke, and Invoke as well as the constructor method.

 An Example of Func<TResult> Type

class Program
{
static void Main(string[] args)
{
ExampleOfFunc exampleOfFunc = new ExampleOfFunc();
Console.WriteLine("{0}", exampleOfFunc.Addition(exampleOfFunc.Add));
Console.WriteLine("{0}", exampleOfFunc.Addition(
() =>
{
return 100 + 100;
}));
}
}
public class ExampleOfFunc
{
public int Addition(Func<int> additionImplementor)
{
if (additionImplementor != null)
return additionImplementor();
return default(int);
}
public int Add()
{
return 1 + 1;
}
}

This program will produce the following output:
2
200

Cheers!!
Mani Kumar Yegateeli



No comments:

Post a Comment