I have two or more variables of class object in c# which has integer values. i want to overload ‘+’ operator so that i won’t have to convert these variables when ever i want to add or subtract them. here is my code below:
public static object operator +( object obj1, object obj2)
{
object o = Convert.toint32(obj1) + Convert.toint32(obj2);
return o;
}
no the problem is i am getting an error saying "One of the parameters of a binary operator must be the containing type"
why is this happening? any help is appreciated!
The compiler error tells you exactly what’s wrong – if you’re going to create a custom binary operator, at least one of the parameter types (for the operands) has to be the same as the type you’re declaring the operator in (or a nullable version of it, for value types).
This is mandated in section 10.10.2 of the C# 4 specification:
Personally I would try to avoid having variables of type
objectif you know they’re actuallyintvalues. Why not haveintvariables instead?If you’re using C# 4, another alternative would be to make them
dynamicvariables, where the operator overloading would be applied at execution time rather than compile time.