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);
The Types you are looking for are
Action<>
orFunc<>
.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 useFunc
whereby the last generic parameter is the return type.For example:
You can use the
dynamic
keyword. See dynamic (C# Reference).<unknown type>
=Function
. That is,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 useFunc<float, Float>
as noticed by others. This is exactly equivalent. In fact,Func<T, T>
is declared in exactly the same way as your delegateFunction
except that it’s generic.Your lambda expressions would take a
float
as a parameter (I believe), and then return afloat
as well. In .NET, we can represent this by the typeFunc<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.The return type is
Func<float, float>
.