“Method must have a return type” and “a return keyword must not be followed by an object expression” errors

There are two ways the class could work… static or instanced.

Instanced

If you want the main method to work this way….

Addition addi = new Addition();
Console.WriteLine("The answer of both {0} and {1} is {2}", num1, num2, addi);

then your Addition class should be more like this:

class Addition
(
    private readonly int result;

    public Addition(int num1, int num2)
    {
        result = num1 + num2;
    }

    public override string ToString()
    {
        return result.ToString();
    }
}

Then it will work with a small change:

Addition addi = new Addition(num1, num2);  //Have to pass the values in
Console.WriteLine("The answer of both {0} and {1} is {2}", num1, num2, addi);

Static

A static method requires no instance, so you have to change this:

Addition addi = new Addition();  
Console.WriteLine("The answer of both {0} and {1} is {2}", num1, num2, addi);

To this:

var addi = Addition.Add(num1, num2);
Console.WriteLine("The answer of both {0} and {1} is {2}", num1, num2, addi);

And your class should look like this:

static class Addition
{
    static public int Add(int num1, int num2)
    {
        return num1 + num2;
    }
} 

Leave a Comment