I need to count all checked checkboxes and I was meaning to use operator overloading as this example :
public static int operator +(bool b1, bool b2)
{
int i1 = 0;
int i2 = 0;
if (b1) i1 = 1;
if (b2) i2 = 1;
return i1 + i2;
}
And then the total would be simply retrieved by
int countCbx = cbx1.Checked + cbx2.Checked + ...
But it don’t work and I don’t see why. The compilation error is “One of the parameters of a binary operator must be the containing type”.
The logic seems good, but it’s the first time I use operator overload outside example.
Thanks for your help.
Because the language specification says so. The compiler is basically giving you the reason.
The logic of the body of the member is fine – but you can’t overload operators for arbitrary types. At least one of the operands (or the return type for conversions) has to be the type that you’re declaring the operator in.
The C# 5 specification contains this in section 10.10:
That rule is then enforced in 10.10.1:
…. 10.10.2:
… and 10.10.3: