28 November 2017

stop creating your own delegates, start using Func delegates

If you are still defining custom delegates, you can stop creating them. In place of them, you can use Action And Func delegates. Sounds cryptic!, don't worry, we will go into detail.

How we define custom delegates?

Delegates are function pointers, which are defined like below.

public delegate string MessageFormat(string text);

And then you will use the delegate to assign a method returning string by accepting a string argument.

public string BuildText(string format){

// logic goes here.

}

//Later you can assign a method returning string
// to the delegate defined
MessageFormat=BuildText;

So in practice, every time you need a new delegate to match the signature of the target method which returns something. In this way, you end up creating new delegates just to match the target method signatures. Creating custom delegates is no longer necessary in latest C# .NET, you easily use built-in Func Delegates to match the definition of methods returning something; other than void.

Use Func delegates in place of custom delegates

As per MSDN Func delegate Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.

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

Where T in the input and the TResult in the return type. The Func delegates are overloaded to support varying number of input parameters ranging from one input argument T1 to 16 arguments (T16).

Now using Func delegate we can easily avoid creating a new delegate to match the definition of a method which returns a type by accepting parameters. Going by this we can easily replace MessageFormat custom delegate declaration. The same delegate can be written as below:

public Func<stringstring> MessageFormat;

1 comment:

  1. Glad to be one of the visitors on this awe inspiring web site : D.

    ReplyDelete