Behind the Scenes Look at C#: Operators, continued - Can we do that?
(Page 3 of 5 )
I will modify the example to return an int value (not an object of type Number) to prove that we have control over the return type.
using System;
namespace Operators
{
class Class1
{
static void Main(string[] args)
{
Number i = new Number();
i.aNumber = 90;
i.aDecimal = .5m;
int result = i + 9;
Console.WriteLine("the value of i.aNumber = {0}", i.aNumber);
Console.WriteLine("i.ToString() returns {0}", i.ToString());
Console.WriteLine("result = {0}", result);
Console.ReadLine();
}
}
public class Number
{
public int aNumber;
public decimal aDecimal;
public static int operator+(Number num, int x)
{
return num.aNumber + x;
}
public override string ToString()
{
return Convert.ToString(this.aNumber + this.aDecimal);
}
}
}
Compile and run the program and you will get the following result to the console window.

Look at the Main method and you will find that we are able to return a value of type int from the expression "int result = i + 9". This happened because we have modified the operator overload method to return an int value through two steps. First we have replaced the return data type Number by an int, then inside the method we have added the num.aNumber to x, and this is the value that will be returned.
Next: Overload the other way >>
More C# Articles
More By Michael Youssef