Operator overloading in C # - where should the code go?

A bit of a conceptual question:

I create my custom structure in the spirit of Vector3 (3 int values), and I worked with overloading standard operators (+, -, *, /, ==, etc.)

Since I am creating a library for external use, I am trying to comply with FxCop rules. Therefore, they recommend using methods that perform the same function.

Eg..Add (),. Subtract (), etc.

To save code duplication, one of these methods (operator overloading or the actual method) will call the other.

My question is, which should be called, which?

This (and this is just code example):

BUT)

public static MyStruct operator +(MyStruct struc1, MyStruct struct2) { return struc1.Add(struct2); } public MyStruct Add(MyStruct other) { return new MyStruct ( this.X + other.X, this.Y + other.Y, this.Z + other.Z); } 

or

IN)

  public static MyStruct operator +(MyStruct struc1, MyStruct struct2) { return new MyStruct ( struct1.X + struct2.X, struct1.Y + struct2.Y, struct1.Z + struct2.Z); } public MyStruct Add(MyStruct other) { return this + other; } 

I'm really not sure if this is preferable, but I'm looking for a few opinions :)

+6
c #
source share
6 answers

I would go with A). Since operator overloading does not meet the CLS requirements (not all .NET languages ​​support operator overloading), it can be considered as syntactic sugar around the actual Add method.

+24
source share

Or. It really doesn't matter. I would expect the code to be embedded anyway, so go with whatever you think is more readable.

+3
source share

Definitely A.

Ways are the real thing. The method can receive additional parameters, they can be marked as virtual (=> can be redefined), overloaded and, as a rule, the nature of the language is more. Before looking for a practical reason, I think you need to feel it. in addition, the CIL language protocol is not required to support operator overloading and such a clear victory in the method.

+2
source share

Since this is a struct , inheritance is not a problem (otherwise β€œA” simplifies virtual ), so I would go with β€œB”, simply because I expect to call + more than I call Add ... less indirectness.

With a class with a real need for + and inheritance (unlikely), I would go "A".

+1
source share

I would vote for option B, as this is a more intuitive place to see what values ​​/ properties are actually used in the statement.

0
source share

I would also go with A for many of the reasons mentioned above, in particular because I see operator overloading as the syntax mechanism that wraps the actual method.

0
source share

All Articles