- Home /
Return a value for a class?
So I have a serializable class, and I want to be able to get a value simply by referring to the object. At the moment I have to refer to specific values like "statistic.total" when I'd rather just say "statistic".
How might I go about returning the object's value?
I believe you cannot do this, I don't think a class can somehow be like a instance of a class.
Hm... perhaps a struct would describe what I want. A Vector3 is a struct with three variables and a few default values. If you refer to the vector itself, it will provide the variables together.
I'm wondering if there would be a similar thing for classes. If not, learning how to do this with structs would be helpful as well.
Do you want to create a custom defined type (something that holds a load of values together)?
Answer by Bunny83 · Nov 18, 2014 at 12:00 AM
The Vector3 struct is always a struct and a class is always a class. You can implement implicit casting operators, however that should only be done when it's an obvious conversion. The Vector2 / 3 / 4 struct only have a conversion between each other so a Vector2 can be used as Vector3.
Implicit casting only applies when it's obvious for the compiler to which type it should be converted.
Example:
public class Statistic
{
public float total;
public static implicit operator float(Statistic aObj)
{
return aObj.total;
}
}
An instance of that class could be converted implicitly into a float value:
Statistic statistic = new Statistic();
statistic.total = 5;
// ...
float f = statistic;
// f would be "5"
However, in this case it's not really obvious and an conversion like that isn't convenient and shouldn't be implemented like that. Implicit casting isn't ment for laziness but when one type can be used like another. Another example is "Color" and "Color32".