Benny
Benny

Reputation: 8815

overload operator = in c#

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.

Upvotes: 0

Views: 513

Answers (4)

srikar kulkarni
srikar kulkarni

Reputation: 748

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.

Upvotes: 0

Anon.
Anon.

Reputation: 59983

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.

Upvotes: 2

Kaleb Brasee
Kaleb Brasee

Reputation: 51945

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.

Upvotes: 9

Shaun Mason
Shaun Mason

Reputation: 797

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

Are you using a built-in object?

Upvotes: 0

Related Questions