overload operator = in c#

Tag: operator-overloading Author: wazyp200063 Date: 2009-12-01

Is it possible to overload operator = in c#?

when i call =, i just want to copy properties, rather than making the left hand reference to refer another instance.

@Nathan, funny post.
@Nathan: that's a masterpiece. Pretty good advice there.
Maybe you are looking for value type semantics. Aren't structs better for you in this scenario?

Best Answer

The answer is no:

Note that the assignment operator itself (=) cannot be overloaded. An assignment always performs a simple bit-wise copy of a value into a variable.

And even if it was possible, I wouldn't recommend it. Nobody who reads the code is going to think that there's ANY possibility that the assignment operator's been overloaded. A method to copy the object will be much clearer.

comments:

When I read the title of the question I was sincerely hoping this was the answer. Thankfully this isn't yet another way to wreak havoc in C++.

Other Answer1

You can't overload the = operator. Furthermore, what you are trying to do would entirely change the operator's semantics, so in other words is a bad idea.

If you want to provide copy semantics, provide a Clone() method.

Other Answer2

Why not make a .CopyProperties(ByVal yourObject As YourObject) method in the object?

Are you using a built-in object?

comments:

no, user defined class