0

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.

3
  • 2
    On a related note: freeworld.thc.org/root/phun/unmaintain.html. Commented Dec 18, 2009 at 3:04
  • @Nathan: that's a masterpiece. Pretty good advice there. Commented Dec 18, 2009 at 3:12
  • Maybe you are looking for value type semantics. Aren't structs better for you in this scenario? Commented Feb 2, 2010 at 19:16

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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++.
2

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.

Comments

0

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

Are you using a built-in object?

Comments

0

We can Overload = operator but not directly.

using System;
class Over
{
    private int a;
    public Over(int a )
    {   
        this.a = a;
    }

public int A { get => a; }

    public static implicit operator int(Over obj)
    {
        return obj.A;
    }
}
class yo
{
    public static void Main()
    {
        Over over = new Over(10);
        int a = over;
    }
}

Here when you call that operator overloading method , it is calling = operator itself to convert that to int. You cannot directly overload "=" but this way of code means the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.