0

I have the following:

class Program {

    delegate int myDelegate(int x);

    static void Main(string[] args) {

        Program p = new Program();
        Console.WriteLine(p.writeOutput(3, new myDelegate(x => x*x)));

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }
    private string writeOutput(int x, myDelegate del) {
        return string.Format("{0}^2 = {1}",x, del(x));
    }
}

Is the method writeOutput in the above required? Can the following be re-written, without writeoutput, to output the same as the above?

Can the line Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x)); be amended so that 3 is fed into the function?

class Program {

    delegate int myDelegate(int x);

    static void Main(string[] args) {

        Program p = new Program();

        Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }
}
2
  • Unless you're practicing the use of delegates, I don't see why it would be necessary in your code. You have the value, and you know what to do with it. Commented Feb 3, 2013 at 13:49
  • @AndersonSilva - right the first time - I'm sand-pitting delegates and lambda functions Commented Feb 4, 2013 at 8:16

3 Answers 3

1

It obviously can't be written that way. Think about this: what value x has in the second code? you create an instance of your delegate, but when it is called?

Use this code:

myDelegate myDelegateInstance = new myDelegate(x => x * x);
Console.WriteLine("x^2 = {0}", myDelegateInstance(3));
Sign up to request clarification or add additional context in comments.

Comments

1

You fon't really need a delagate. But in order to work you need to change this line:

    Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));

with this:

    Console.WriteLine("{0}^2 = {1}", x, x*x);

1 Comment

+1 thanks Petar - but the point of the exercise is that I'm trying to understand delegates and how lambdas relate to them
1

Firstly, you don't need a delegate. You can just multiply it directly. But first, the correction of the delegate.

myDelegate instance = x => x * x;
Console.WriteLine("x^2 = {0}", instance(3));

You should treat every instance of a delegate like a function, in the same way you do it in the first example. The new myDelegate(/* blah blah */) is not necessary. You can use a lambda directly.

I assume you're practicing the use of delegates/lambdas, because you could just have written this:

Console.WriteLine("x^2 = {0}", 3 * 3);

1 Comment

+1 exactly - just practicing delegates/lambda and trying to get my head around how they work

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.