Generic Delegates Implementation

The Func<TResult> delegate defines a method that can be called on arguments and returns a result.

Example: you are having a method which is not taking any arguments but that method is returning string or bool or any kind of return types the generic Delegate declaration will be….

  1. public static string getHello()  
  2. {  
  3.     return "Hello";  
  4. }  
  1. Func<string> gethelloAdvanced = getHello;  
  1. Func < string > gethelloAdvanced = delegate()  
  2. {  
  3.     return "hello";  
  4. };  
  1. Func<string> gethelloAdvanced = () => "hello";  

Above there declarations are equal but syntactically different from each other.

Invoking above delegate as follows

gethelloAdvanced()

Above statement will resturn “Hello” string.

Generic Delegate(Func<T,TResult>):

The Func<T,TResult> delegate defines a method that can be called with one arguments and returns a result.

Example: you are having a method which is taking one arguments and that method is returning string or bool or any kind of return types the generic Delegate declaration will be….

  1. public static string getUpperresult(string str)  
  2. {  
  3.     return str.ToUpper();  
  4. }  
  1. Func<string,string> ConvertToUpper= getUpperresult;  
  1. Func < stringstring > ConvertToUpper = delegate(string str)   
  2. {  
  3.     return str.ToUpper();  
  4. };  
  1. Func<stringstring > ConvertToUpper = str =>str.ToUpper();  
Invoking above delegate as follows

ConvertToUpper(“Random text”)

Above line of code will take one string as an parameter and return upper case string.
  1. Func<stringstringstring> result = (s1, s2) =>  
  2. S1+” and ”+s2;  
Note: Depending on Parameters will change accordingly as follows.
  1. Func<T1,T2, T3, T4……Tn,TResult> result =(s1, s2,……,Sn) =>  
  2.   S1+” and ”+s2+……..+sn;
Ebook Download
View all
Learn
View all