views:

81

answers:

3

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.

A: 

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

Are you using a built-in object?

ShaunLMason
no, user defined class
Benny
+8  A: 

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.

Kaleb Brasee
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++.
Martinho Fernandes
+2  A: 

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.

Anon.