Tutorial Problems

So I was following a tutorial to learn C Sharp, and when there was a particular set of code that I had to write.
Here is the code(the problem zone is highlighted):

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SecondScript : MonoBehaviour
{
int number1 = 2;
int number2 = 3;
int number3 = 7;

void Start()
{

int answer =
AddTwoNumbers(number1, number2) +
AddTwoNumbers(number1, number3);

DisplayResult(answer);

}

void AddTwoNumbers(int firstNumber, int secondNumber)
{

int result = firstNumber + secondNumber;
return result;

}

void DisplayResult(int total)
{

Debug.Log("The grand total is: " + total);

}

}

I copied the code exactly and then the following errors:

Assets/Code/Scripts/LearningScript.cs(17,8): error CS0019: Operator +' cannot be applied to operands of type void’ and `void’

and

Assets/Code/Scripts/LearningScript.cs(30,9): error CS0127: `SecondScript.AddTwoNumbers(int, int)': A return keyword must not be followed by any expression when method returns void

I’m quite new to C Sharp so if I’m making a very obvious mistake please tell me.

If you can help thanks/

When you declare a method the value type (int, string, objects, etc…) that precedes the name of the method determines with it will return. In the method you have:

void AddTwoNumbers(int firstNumber, int secondNumber)
{
int result = firstNumber + secondNumber;
return result;
}

The void keyword is telling the compiler that the method returns nothing but at the end you have “return result” which is telling it to return the integer. To fix it just replace the void with the int keyword.

1 Like

Thank you that worked perfectly