public int CalculateProduct(int num1, int num2) Requires a return type of int. However, in main, when CalculateProduct is called, no variable is assigned to accept the int being returned. I don't understand why. Thanks!

using System;

delegate void NotifyCalculation(int x, int y, int result);

class Calculator {
    NotifyCalculation calcListener;

    public Calculator(NotifyCalculation listener) {
        calcListener = listener;
    }

    // THIS IS NOT A VOID. IT HAS A RETURN TYPE OF INT
    public int CalculateProduct(int num1, int num2) {
        // perform the calculation
        int result = num1 * num2;
        // notify the delegate that we have performed a calc
        calcListener(num1, num2, result);
        // return the result
        return result;
    }
}

class CalculationListener {
    public static void CalculationPrinter(int x, int y, int result) {
        Console.WriteLine("Calculation Notification: {0} x {1} = {2}", 
            x, y, result);
    }
}

class Listing_04 {

    static void Main(string[] args) {

        // create a new Calculator, passing in the printer method
        Calculator calc = new Calculator(CalculationListener.CalculationPrinter);


        // THE RETURN TYPE IS NOT BEING CAPTUREED HERE WHY?
        calc.CalculateProduct(10, 20);
        calc.CalculateProduct(2, 3);
        calc.CalculateProduct(20, 1);

        // wait for input before exiting
        Console.WriteLine("Press enter to finish");
        Console.ReadLine();
    }


}

Recommended Answers

All 2 Replies

The return value doesn't have to be stored. It is up to the programmer to determine what to do with a return value, or whether to not use it all together. In this case, the programmer decided to use an delegate to print the result and didn't need it for anything else in the Main method.

Hope that helps.

commented: Thanks! +0

So you are saying as a general rule that if a method has a return type it doesn't have to be stored or captured when the method is called?

Because the author introduces different types of new syntax in the chapter on Delegates, I went back and read the chapter on Methods. He talks about return types in two sections in the chapter but NEVER ONCE says anything about capturing the return in the code calling the method as being optional. I just double checked and he says nothing about it.

Coming from a VB6 background, i know functions (storedprocedures with return values) required something to capture the value. So i assumed it must be true here was well.

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.