Behind the Scenes Look at C#: Operators, continued - Overload the other way
(Page 4 of 5 )
With the same example, replace the Main method with the following updated code and try to compile the application.
static void Main(string[] args)
{
Number i = new Number();
i.aNumber = 90;
i.aDecimal = .5m;
int result = 9 + i;
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();
}
This code will not compile, and it will generate the following error "Operator '+' cannot be applied to operands of type 'int' and 'Operators.Number.'" What happened? We have written an expression that consists of a constant field of type int, then the + operator, followed by an instance of type Number, so what's wrong?
Actually the operator overload method we wrote has a signature that accepts the Number instance first, then the int variable. As you know, the parameters' order is very important, so the compiler has generated an error. To solve this problem we need to write another method that accepts an int parameter followed by the Number type parameter.
public static int operator+(int x, Number num)
{
return num.aNumber + x;
}
and this is the complete code example
using System;
namespace Operators
{
class Class1
{
static void Main(string[] args)
{
Number i = new Number();
i.aNumber = 90;
i.aDecimal = .5m;
int result = 9 + i;
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 static int operator+(int x, Number num)
{
return num.aNumber + x;
}
public override string ToString()
{
return Convert.ToString(this.aNumber + this.aDecimal);
}
}
}
Next: Operator overloading, revisited >>
More C# Articles
More By Michael Youssef