C# Operator Overloading

bri189a

Well-known member
Joined
Sep 11, 2003
Messages
1,004
Location
VA
Im learning how to do this and Im 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 dont use the ref or the out keyword the parameter you pass are changed, so it has seemed in my testing. If its not how to you pass it by ref; basically this class that Im making has to be very fast, creating a copy of the object would waste to much memory so I want to edit the original, Ive tried the ref, out, *, & (using unsafe for the last two) and I get all sorts of weird errors, but if youre already passing it by ref anyway, then I dont really need to use those. Thanks for any help with this. The operator overloading Im 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 wouldnt 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 ive 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. Im making a 3D vector class... I know .NET isnt the ideal environment for that, but its practice and learning more than anything, I got it working but its the semantics Im 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) Im just doing myVector+=10; saves a few steps, horrible example but hoepfully that clarifies what it is Im 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, thats 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 couldnt change any instance variables and IIRC they do not allow parameters to be declared ref.
 
Back
Top