FVNTUM FVNTUM - 3 months ago 12
C# Question

Not All Code Paths Return A Value (C#)

I'm currently learning C# and I'm having trouble with this program. I'm learning about methods and classes and I'm making a test program that adds two numbers together and displays them in the console. I receive the following three errors:

prog.cs(5,13): error CS0161: `Test.addNumbers(int, int)': not all code paths return a value
prog.cs(16,3): error CS0118: `Test.addNumbers(int, int)' is a `method' but a `type' was expected
prog.cs(17,7): error CS0841: A local variable `numbers' cannot be used before it is declared
Compilation failed: 3 error(s), 0 warnings


Here is my code:

using System;

public class Test
{
public int addNumbers(int num1, int num2) {
int result;
result = num1 + num2;
}

public static void Main()
{
int a = 2;
int b = 2;
int r;

addNumbers numbers = new addNumbers();
r = numbers.addNumbers(a, b);

Console.WriteLine(r);
}
}


I've tried everything that I know of, but as I said, I'm still learning so I don't know much about C#. Can anyone please explain to me what the errors mean, why they occurred and how to fix them? Thank you.

Answer

Modify your addNumbers to return a value. Function signature states it returns int, so you must return int from the function.

using System;

public class Test
{
    public static int addNumbers(int num1, int num2) 
   {
    int result;
    result = num1 + num2;
    return result;
    }

    public static void Main()
    {
        int a = 2;
        int b = 2;
        int r;


        r = addNumbers(a, b);

        Console.WriteLine(r);
    }
}

EDIT:

You need addNumbers numbers = new addNumbers(); only if your function is not static.

Static functions can be called with ClassName.FunctonName, while non/static (instance functions) need to be called in a way you described.

addNumbers numbers = new addNumbers();
numbers.SomeFunction();

You can look it following way.

Classname.SomeStaticVariable = 2;

Way described above, SomeStaticVariable would be same for the entire application at any point. While way described below would be available only while obj exists in the memory.

Classname obj = new ClassName();
obj.SomeVariable = 2;