Tuesday, October 28, 2014

Func Delegate Using Lambda Expression in C#

Func Delegate Using Lambda Expression in C#

In this article I'll try to explain a cool feature introduced with .NET 3.5. Known as Func, also named by some developer as a readymade delegate.
Func encapsulates a method with two parameters and returns a value of the type specified by the TResult parameter. It has a few overloaded methods as depicted below:

Func1.jpg
If you look into the image shown above then it shows you five overloaded methods.

Definition of Func<>
I've used a delegate that contains the following syntax defined as below:
Func2.jpg
Now let's discuss how it works and accepts parameters. In the Func<> delegate there are three params being passed, the first one is of string type named "a", the second "b" is also a string type and the third is a result type that is also a string type.
Func3.jpg
If you find the definition of Func using F12 then it gives you the following details:
image
Internally it's a delegate that accepts two params and returns a TResult.

At the initial level of code segment I've set a description that contains some delimiters. My task is to remove all of it from the description.


  1: string description = "<b>Hi Welcome to world of .net</b> ,There are lot of new and emerging things into .net</br>"
  2:                                  + "<h1>Make it your passion to help community and cheer for every moment</h1></br>"
  3: 
  4: Declaration of Func<>
  5: 
  6: Func<string, string, string> replaceExtra = (a, b) => a.Replace(b, string.Empty);


The purpose of this delegate is to replace all the occurrences of delimiters like "<b>,</b>,</br><h1></h1>".


Use of replaceExtra Func<>

The code segment shown below uses the replaceExtra that takes two params (both are of string type) and returns the value as a string type also.


  1: description = replaceExtra(description, charsToReplace[0]);



Now let's run this and examine the working behavior:
When we run the program initially without using the replaceExtra Func<> delegate, it prompts the following screen:


Func5.jpg
Now I use the following lines of code and try to replace all occurrences of delimiters:


  1: description = replaceExtra(description, charsToReplace[0]);
  2: description = replaceExtra(description, charsToReplace[1]);
  3: description = replaceExtra(description, charsToReplace[2]);
  4: description = replaceExtra(description, charsToReplace[3]);


Again press F5 and see the magic of Func<>.


Func6.jpg


You can download a sample application from here:

Func Delegate Using Lambda Expression in C#


Hope you enjoyed this demonstration.

To learn more about MVC please go to the following link.
MVC Articles

Download FuncDelegate Example

Thanks

Enjoy Coding and Readingclip_image017


0 comments :

Post a Comment