C# Operator Overloading

bri189a

Senior Contributor
Joined
Sep 11, 2003
Messages
1,004
Location
VA
I'm learning how to do this and I'm looking to see if I got this correct. Normally when you pass arguments to a function, unless you pass it with the ref or the out keyword, the parameter comes back unchanged, even if you change it in the function, but with operator overloading, even though you don't use the ref or the out keyword the parameter you pass are changed, so it has seemed in my testing. If it's not how to you pass it by ref; basically this class that I'm making has to be very fast, creating a copy of the object would waste to much memory so I want to edit the original, I've tried the ref, out, *, & (using unsafe for the last two) and I get all sorts of weird errors, but if you're already passing it by ref anyway, then I don't really need to use those. Thanks for any help with this. The operator overloading I'm doing is the !=, +, -, *, and /, it also appears that I need to overload Equals and HashCode by the warnings that come up, is this true or can I simply pass base.HashCode for the HashCode and overload the Equals to do the basic same function as the ==.

Thanks again!
 
If you want to edit the original then operator overloading wouldn't make much sense syntax wise...

e.g
C#:
int i,j;
i=0;
j=i+4;
j would equal the value of i with 4 added to it - it would not affect the value of i itself however.
If i've missed the point (quite possible - been awake too long today) could you give a code (or pseudo code) example of what you are trying to do / would like to do ?
 
PD - no problem been there myself. I'm making a 3D vector class... I know .NET isn't the ideal environment for that, but it's practice and learning more than anything, I got it working but it's the semantics I'm concerned about (programming correct vice incorrectly and working ineffiecently). As you probably know a vector can be added to subtracted and so on.

So rather than going myVector = new Vector3D(myVector.X += 10, myVector.Y +=10, myVector.Z += 10) I'm just doing myVector+=10; saves a few steps, horrible example but hoepfully that clarifies what it is I'm trying to do. Like I said I got it working just setting up the parameter w/o any ref or out, just normal, and it appears it modifies the variable directly, but I just want to make sure, that's all.

Thanks
 
myVector += 10 is just shorthand for myVector=myVector + 10 and as such the operator+ should be doing the adition and returning a new instance of the Vector class.
Overloaded operators need to be declared static anyway so they couldn't change any instance variables and IIRC they do not allow parameters to be declared ref.
 
Back
Top