Hello Everyone, In this article we will talk about Func< in T, out TResult>Delegate.
It is another readymade delegate that provides
by .Net framework. It can encapsulate a method that takes some parameters as
input and returns an output as TResult.
So in general Func is a delegate
1. Which takes from 0 to 16 parameters.
2.It is contra variant
and co variant both. Input parameters are contra variant and Output parameters
are co variant.
Where can we use Func delegate ?
You can use this delegate to encapsulate a method where you
need to pass some parameter( 0 to 16 ) and need to get some result. In this
case you do not need to explicitly create a delegate. Func is perfect
Let's see a complete example of Func delegate -
Use case - Let's say An array is given and you have
to print only odd numbers.
Solution - You can create a foreach loop and
checkif the number is odd then print
At later stage of development you get some more rules added.
Let's say print those odd numbers which are greater than 5.
So in this case you have to modify your for loop which can
be at the UI level. In that case we will break some SOLID rules.
the solution ?
We can create a Func that takes input of array and apply all
the rules and return list of data or one by one. This can be at model level and
UI won't be aware of the logic and functionality.
Hope you like reading the article. Please inbox me in case
of any confusion.
Hello everyone, in this article we will talk about “Action” a readymade delegate. Action is just another delegate that takes some parameters and doesn’t return a value. So when do you want to execute some method which doesn’t return any value then rather creating your own delegate. .Net framework provides us an Action Delegate. Please have a look on below image –
So In general Action is a delegate -
Which is contra variant ( in parameterwill discuss this in next articles )
Which takes 1 to 16 parameters but do not return any value.
So let’s take an example of using Action –
Action obj = new Action(MyDummyMethod);
// You can call it as asynchronous way because this is just a delegate
Cool J So we saw in this example we can invoke an action as a synchronous way as well as asynchronous way because Action is none other than a delegate.
Hello Everyone, I talked about delegate in my last article. In this article we will talk about multicast delegate.
A Delegate is a type variable that holds the reference of a method and multicast delegate can holds the reference of multiple methods. So basically it's kind of linked list of methods. When we execute the multicast delegate then all the methods which are associated with the multicast delegate will execute in sequence.
How can we create a multicast delegate ?
There is no difference in creation of Delegate and Multicast Delegate. It's just we can associate multiple methods with the same delegate.
Now the question is how can we associatemultiple methods to a delegate ?
There are two ways of associating multiple methods -
Or myDelA += MethodB;
Let's see the example -
So now question is How multicast delegate reference to the methods and invoke it ?There is a method exposed in delegate from which we can fetch the invocation listand that list returns the collection of all the associated delegates.
So in the above example I have not called invoke method of delegate directly. Instead of fetching all the method info from GetInvocationList() and invoking it one by one. This is the way .Net framework calls the method in sequential way.
Let's say if some of the method throws exception then how multicast delegate handles that situation ?
Have a look on below Example this is the answer of the question -
myDel multiCast = MethodC;
multiCast += MethodD;
//If you will call this. This will throw exception//multiCast.Invoke();foreach (myDel del in multiCast.GetInvocationList())
catch (Exception ex)
Console.WriteLine("Executing method D.");
Hope you like reading this article. Please inbox me in case
of any confusion.
Hello Guys, So in the last article we talked about What is
delegate and how can we create a delegate.
In this article we will discuss what are the ways available
to call a delegate and what are the differences in between ?
There are different ways in which you can invoke
delegates to get a synchronous or an asynchronous behavior.
synchronous-Using Invoke we can achieve this and in this delegate
execute synchronously on the same thread. So in general when you want to
invoke a delegate and want to wait for its completion before current thread
continues then Invoke is the right choice. Details you can see in this
Way -We can achieve this using BeginInvoke, It means you
do not want that main thread wait for
the completion of the delegate. In this scenario the delegate and current
thread can work in parallel.
Point to notice here is You can achieve Asynchronous way using Delegate.BeginInvoke or
creating a new thread then Which one to prefer and Why ?
Delegate provides a very less control over async behavior as
when you invoke a delegate you can fetch the result using EndInvoke but you cannot
terminate the process. While creating a thread you have more control on Async
behavior. So in my understanding creating a Thread is better than invoking a
delegate in Async way.
of BeginInvoke -
In the above example we saw how can we invoke a delegate
So now in case GenerateMainXml has to return some value. How
can we handle this situation ?
Calling EndInvoke will always block your main thread until
it completes the execution. There are two ways of calling EndInvoke. One is as
a callback and another one is direct way.
Direct way of calling an EndInvoke() -
So in the above example we created a Square number function
and assigned it to a delegate. Called using BeginInvoke and on the same
delegate called the EndInvoke method to get the results.
There is one problem in this approach. Use case of
BeginInvoke is to get asynchronous way of implementing one of the method. But
after calling EndInvoke we are telling to main thread to wait until delegates execution
completes. Then only we can fetch the results .
what is the solution ?
Calling EndInvoke as Callback method. In this
way we tell delegate once it completes the execution, call the callback method and tell us the results.
So main thread won't be blocked.
Looks Good :)
similar to Invoke, it invokes a delegate in asynchronous way. The only benefit
is it takesobject as parameter. So it
does boxing and unboxing at run time.
Correct implementation is -
So we can see in the above example we can pass an object
array as aparameter in dynamicinvoke and the result will also be a object type.
So this is usefule when you are not aware of the type but it will be damn slow.
So think before using it.
Hope you like reading the article. Please inbox me in case
of any confusion is in your mind.
A Delegate is a type variable that holds the reference to a method. Delegates are similar to Pointer to functions in C and C++
When we create a delegate then we can assign a method to delegate instance according to its signature and we can change the reference at run time. After assigning the method we can call this method using delegate instance.
- Your method signature and return type must match with Delegate
Why do we need to create a Delegate ?
Delegate Invoke method at run time.
Delegate can be used for callback methods.
Delegates can invoke multiple methods on a single event. So this is useful when we have to give multiple implementation of a single method.
When do you want to restrict access to caller then we can expose a delegate.
Now How can we create a Delegate ?
publicdelegateintMyPointer(int x, int y);
AccessModifier, delegate type , return type DelegateName(Delegate params)
This is how we can create a Delegate. Now the point is how can we create a Delegate instance and add methods at run time.
So here we created instance of a class MyDelegate and
call the method MyOperation.It returns a delegate instance now we call the
invoke method of delegate.
Now the question comes What is this Invoke ? See below
So delegate has these mentioned methods for instantiation. Currently I am using Invoke method to instantiate the delegate. When we say instantiate it
means delegate call the same method which we attach.
Let's talk about these methods
mentioned above -
- Executes asynchronously on a pooled thread (Thread pooling or TPL)
- Delegate execute synchronously on the same thread.
Delegate execute synchronously but as name says dynamic, you pass the parameter
to function does boxing and unboxing at runtime. It requires an object array to
execute the method. Avoid this as it is Damn Slow.
- This Fetches all the method
info you associated with the Delegate. So it is useful when you want to execute
delegate according to your need. You can fetch the info and invoke accordingly.
We will discuss this in next articles.
Of Delegates :
Multi Cast Delegate
Readymade Delegates - Func, Action and Predicate
In this article we talked about single delegate . In Next
Article we will talk about Multi Cast Delegate and Readymade Delegates in C#
Hope you enjoyed reading the article. Please inbox me in
case of any confusion.
This is my personal blog and i write articles on .Net, WPF, C#, OOPS, Threading and other .Net technologies. This is not related to any of my employer and organizations. This is the result of my personal interest.