- Home /
Return a value from a custom class
Hi all,
I'm fairly new to programming and have been dabbling with C# I'm trying to create a class that returns a value, for example
using UnityEngine;
using System.Collections;
public class addValues : MonoBehaviour
{
int val1;
int val2;
public addValues (int val1, int val2)
{
this.val1 = val1;
this.val2 = val2;
int answer = val1 + val2;
return answer;
}
}
but I get the error "A return keyword must not be followed by any expression when method returns void" Is the default return type void? How would I go about allowing it to return the value?
Thanks in advance
Answer by Jamora · Feb 28, 2014 at 10:29 AM
Classes cannot return values. Classes are a container for data and functionality to modify that data. What you're trying to do here is create a new object from this class. Creating objects is accomplished using a constructor, which is what you're trying to do here.
Usually classes are not made around functionality (such as adding), instead you would name your class something like NumberPair, which then contains two numbers and has methods which will return the result of operations on those numbers.
using UnityEngine;
using System.Collections;
public class addValues : MonoBehaviour
{
int val1;
int val2;
public addValues (int val1, int val2)
{
this.val1 = val1;
this.val2 = val2;
}
public int Add(){
return val1+val2;
}
}
Now you would use use this Add function by first creating a new object of type addValues (really should rename this -- Class names in C# are, by convention, Capitalized) with the following line of code:
addValues addition = new addValues(3,6); //create object
int result = addition.Add(); //perform the addition
Ah, that makes so much more sense! Brilliant, Thanks guys!
Ah, that makes so much more sense! Brilliant, thanks guys!
Answer by moghes · Feb 28, 2014 at 10:26 AM
Dude, your function type must be of the same type of your returning value.
like down there, you are returning answer which is of type "int", so have your function of type int. check the code edited.
public class addValues : MonoBehaviour
{
int val1;
int val2;
public int addValues (int val1, int val2)
{
this.val1 = val1;
this.val2 = val2;
int answer = val1 + val2;
return answer;
}
}
Answer by zedsmith52 · May 27, 2018 at 01:43 AM
It seems you have a little confusion between classes and functions. Both answers above are valid and correct, just remember to take some care not to get the two mixed up.
Simply, a class is used to create and object more complex (generally) than native types, such as int, float, etc.
Functions are generally used to perform operations.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Will calling and instance of classA, from classA, repeatedly, cause a stack overflow? 1 Answer
Parent Class variables in Child Class's Inspector (C#) 0 Answers
Field is never assigned to, and will always have its default value 3 Answers