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:
The following rules apply to binary operator declarations, where T denotes the instance type of the class or struct that contains the operator declaration:
- A binary non-shift operator must take two parameters, at least one of which must have type T or T?, and can return any type.
- A binary
<<
or>>
operator must take two parameters, the first of which must have type T or T? and the second of which must have type int or int?, and can return any type.
Personally I would try to avoid having variables of type object
if you know they're actually int
values. Why not have int
variables instead?
If you're using C# 4, another alternative would be to make them dynamic
variables, where the operator overloading would be applied at execution time rather than compile time.
You can't override the operator for existing classes: only your own classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With