Miro
Miro

Reputation: 1806

Can a C# method return a method?

Can a method in C# return a method?

A method could return a lambda expression for example, but I don't know what kind of type parameter could I give to such a method, because a method isn't Type. Such a returned method could be assigned to some delegate.

Consider this concept as an example:

public <unknown type> QuadraticFunctionMaker(float a , float b , float c)
{
    return (x) => { return a * x * x  + b * x + c; };
}

delegate float Function(float x);
Function QuadraticFunction = QuadraticFunctionMaker(1f,4f,3f);

Upvotes: 45

Views: 66261

Answers (5)

Zebi
Zebi

Reputation: 8882

The Types you are looking for are Action<> or Func<>.

The generic parameters on both types determine the type signature of the method. If your method has no return value use Action. If it has a return value use Func whereby the last generic parameter is the return type.

For example:

public void DoSomething()                          // Action
public void DoSomething(int number)                // Action<int>
public void DoSomething(int number, string text)   // Action<int,string>

public int DoSomething()                           // Func<int>
public int DoSomething(float number)               // Func<float,int>
public int DoSomething(float number, string text)  // Func<float,string,int>

Upvotes: 53

Ahmed Magdy
Ahmed Magdy

Reputation: 6030

You can use the dynamic keyword. See dynamic (C# Reference).

Upvotes: -6

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19339

Your lambda expressions would take a float as a parameter (I believe), and then return a float as well. In .NET, we can represent this by the type Func<float, float>.

Generally, if you're dealing with lambdas that take more parameters, you can use Func<Type1, Type2, Type3, ..., ReturnType>, with up to eight parameters.

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545488

<unknown type> = Function. That is,

public Function QuadraticFunctionMaker(float a , float b , float c)
{
    return (x) => { return a * x * x  + b * x + c; };
}

Is what you’re looking for since you’ve already declared the delegate Function to match. Alternatively, you don’t need to declare a delegate at all and can use Func<float, Float> as noticed by others. This is exactly equivalent. In fact, Func<T, T> is declared in exactly the same way as your delegate Function except that it’s generic.

Upvotes: 3

siride
siride

Reputation: 209445

public Func<float, float> QuadraticFunctionMake(float a, float b, float c) {
    return x => a * x * x + b * x + c;
}

The return type is Func<float, float>.

Upvotes: 28

Related Questions