2

Hi I'm learning about using Lambda from a book. After I copied a piece of code from the book to VS2010 I got the error:

Delegate 'System.Func<float>' does not take 1 arguments"

VS2010 marked the error under the left parenthesis at line 3, before "float x". Can you tell me what is wrong?

static void Main(string[] args)
{
    Func<float> TheFunction = (float x) =>
    {
        const float A = -0.0003f;
        const float B = -0.0024f;
        const float C = 0.02f;
        const float D = 0.09f;
        const float E = -0.5f;
        const float F = 0.3f;
        const float G = 3f;
        return (((((A * x + B) * x + C) * x + D) * x + E) * x + F) * x + G;
    };

    Console.Read();
}

3 Answers 3

9

You're trying to write a function which accepts a float input, and returns a float output. That's a Func<float, float>. (To give a clearer example, if you wanted a delegate with an int parameter and a return type of float, that would be a Func<int, float>.)

A Func<float> would have no parameters, and a return type of float. From the documentation of Func<TResult>:

Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.

public delegate TResult Func<out TResult>()
Sign up to request clarification or add additional context in comments.

2 Comments

because you look a little short of rep +1
@Garry You're voting for the answer, not the book.
4

Because a Func<T> represents a delegate which returns a value of type T. From MSDN:

Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.

What you want is a Func<float, float>—that is, a delegate which accepts a float as a parameter and returns a value of type float.

Comments

0

The final parameter in a Func is the return type, the others are the argument types. For Func with a, b, c as parameters, a and b are the argument types, c is the return type.

Func<int, int, double> func = (a,b) => a + b;
int aInt = 1;
int bInt = 2;
double answer = func(aInt, bInt); // answer = 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.