Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I describe an Action<T> delegate that returns a value (non-void)?

Tags:

c#

.net

delegates

The Action<T> delegate return void. Is there any other built-in delegate which returns non void value?

like image 917
user496949 Avatar asked Nov 12 '10 04:11

user496949


People also ask

Can delegate return a value?

If you have a method that accepts two numbers and you want to add them and return the sum of the two numbers, you can use a delegate to store the return value of the method as shown in the code snippet given below. int result = d(12, 15);

What Is an Action delegate?

Action delegate is an in-built generic type delegate. This delegate saves you from defining a custom delegate as shown in the below examples and make your program more readable and optimized. It is defined under System namespace.

What is delegate void?

public delegate void Del(string message); A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with a lambda expression. Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method.

Is a delegate that can hold the reference of a method that does not return any value?

The myDelegate is a user-defined name of the delegate that takes a single integer parameter and its return type is void that does not return any value.


Video Answer


2 Answers

Yes. Func<> returns the type specified as the final generic type parameter, such that Func<int> returns an int and Func<int, string> accepts an integer and returns a string. Examples:

Func<int> getOne = () => 1; Func<int, string> convertIntToString = i => i.ToString(); Action<string> printToScreen = s => Console.WriteLine(s); // use them  printToScreen(convertIntToString(getOne())); 
like image 116
Anthony Pegram Avatar answered Oct 08 '22 19:10

Anthony Pegram


Sure, the Func Delegates return T.

Func<TResult> is "TResult method()" Func<TInput, TResult> is "TResult method(TInput param)" 

All the way down to

Func<T1, T2, T3, T4, TResult> 

http://msdn.microsoft.com/en-us/library/bb534960.aspx

http://msdn.microsoft.com/en-us/library/bb534303.aspx

Also, for the sake of completeness, there is Predicate which returns bool.

Predicate<T> is "bool method(T param)" 

http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx

like image 26
Michael Stum Avatar answered Oct 08 '22 20:10

Michael Stum