I am trying to do operator overloading on a class. I was guided by the example that Microsoft gives on its page.
Operator overloading (C# reference)
But I'm getting some errors and I don't know how to fix it:
DataObject.cs(8,49): Error CS1002: Expected ; DataObject.cs(8,57): Error CS1519: The token '+' is invalid in a class, struct, or interface member declaration DataObject.cs(8,65): Error CS1519: The token ';' is not valid in a class, struct, or interface member declaration
This is my code:
//--------------------------------------------------
public class DataObject<T>
{
private T data;
public static DataObject<T> operator +(DataObject<T> b) => data + b.data;
}
//--------------------------------------------------
public class Int : DataObject<int>
{
}
//--------------------------------------------------
public class Calcula
{
public Int Suma(Int a, Int b)
{
return a + b;
}
public void Suma(Int a, Int b, Int result)
{
result = a + b;
}
}
//--------------------------------------------------
public class EntryPoint
{
static void Main()
{
Int a = new Int();
Int b = new Int();
Int result = new Int();
Calcula calcula = new Calcula();
a = 5;
b = 7;
calcula.Suma(a, b, result);
Console.Write("\n result=" + result);
a = 3;
b = 6;
result = calcula.Suma(a, b);
Console.Write("\n result=" + result);
}
}
Could someone tell me how to do this correctly? Thank you so much!!
You could try something like what I'll show you below.
The key is to use methods that return references. Here the official documentation doc
And here you have the Main method, where different Tests are carried out and, it seems, it fulfills what you want:
Don't forget to add validations to the methods of the Operator class.
At the moment I have reached this solution... but I don't like it because I lose the instances of the original objects and I would like to keep them... If someone knows how to do the same but keeping the instances and puts his answer here I will accept it.
NOTE: I don't use a static instance because if not I can only declare a single object.
Program output:
Thank you very much!!