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….
- public static string getHello()
- {
- return "Hello";
- }
- Func<string> gethelloAdvanced = getHello;
- Func < string > gethelloAdvanced = delegate()
- {
- return "hello";
- };
- 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….
- public static string getUpperresult(string str)
- {
- return str.ToUpper();
- }
- Func<string,string> ConvertToUpper= getUpperresult;
- Func < string, string > ConvertToUpper = delegate(string str)
- {
- return str.ToUpper();
- };
- Func<string, string > 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.
- Func<string, string, string> result = (s1, s2) =>
- S1+” and ”+s2;
Note: Depending on Parameters will change accordingly as follows.
- Func<T1,T2, T3, T4……Tn,TResult> result =(s1, s2,……,Sn) =>
- S1+” and ”+s2+……..+sn;