jameskind
jameskind

Reputation: 1107

Is there a delegate that combines the functionality of Func<T> and Action<T>?

When you call a Action<T> you will pass in a variable of type T which will be available to the code defined in the delegate, e.g.

var myAction = new Action<string>(param =>
{
    Console.WriteLine("This is my param: '{0}'.", param);
});

myAction("Foo");

// Outputs: This is my param: 'Foo'.

And when you call a Func<T> the delegate will return a variable of type T, e.g.

var myFunc = new Func<string>(() =>
{
    return "Bar";
});

Console.WriteLine("This was returned from myFunc: '{0}'.", myFunc());

// Outputs: This was returned from myFunc: 'Bar'.

Here's the question -

Is there a third delegate type which will take an input parameter and also return a value? Something like -

var fooDeletegate = new FooDelegate<string, int>(theInputInt =>
{
    return "The Answer to the Ultimate Question of Life, the Universe, and Everything is " + theInputInt;
});

Console.WriteLine(fooDeletegate(42));

// Outputs: The Answer to the Ultimate Question of Life, the Universe, and Everything is 42

If such a thing doesn't exist, would it possible to use Action<Func<sting>> for this sort of functionality?

Upvotes: 0

Views: 269

Answers (3)

S&#246;ren
S&#246;ren

Reputation: 2731

you can do this with new Func<inputType1, inputType2, inputType3, outputType>(). This is possible with 0 to 16 input parameters. You will find the different Func overloads in the System namespace.

Upvotes: 2

Mark Sowul
Mark Sowul

Reputation: 10600

There are Func<> overloads with [more than zero] parameters Func<TParam, TReturn>, Func<TParam1, TParam2, TReturn>, etc.

Upvotes: 2

SLaks
SLaks

Reputation: 887415

You're looking for Func<T, TResult>, or one of its 15 other overloads.

Upvotes: 16

Related Questions