Return Types

You’ve seen in several places so far in this book that methods can return a type, or they can return nothing at all if the return type is void. You’ve mostly used void methods up until now, specifically Main( ), although WriteLine( ) is a void method as well. The constructors you’ve worked with do return a value—they return an instance of the class.

What you may not know is that you can use a method call in place of an object, if the method returns the appropriate type. For example, suppose you have a class Multiplier, such as this:

public class Multiplier
{
    public int Multiply(int firstOperand, int secondOperand)
    {
        return firstOperand * secondOperand;
    }
}

You can call that Multiply( ) method anyplace you’d expect an int, like this:

int x = 4;
int y = 10;
Multiplier myMultiplier = new Multiplier( );
int result = myMultiplier.Multiply(x, y);

Here, you’re assigning the return value of the Multiply( ) method to an int, which works fine, because the return type of the Multiply( ) method is int. You can do the same with any of the intrinsic types, or with classes you create.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.