Reputation: 1806
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
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
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
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
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