Overloading Assignment Operator in C#

Overloading assignment operator in C#

It sounds like you should be using a struct rather than a class... and then creating an implicit conversion operator, as well as various operators for addition etc.

Here's some sample code:

public struct Velocity
{
private readonly double value;

public Velocity(double value)
{
this.value = value;
}

public static implicit operator Velocity(double value)
{
return new Velocity(value);
}

public static Velocity operator +(Velocity first, Velocity second)
{
return new Velocity(first.value + second.value);
}

public static Velocity operator -(Velocity first, Velocity second)
{
return new Velocity(first.value - second.value);
}

// TODO: Overload == and !=, implement IEquatable<T>, override
// Equals(object), GetHashCode and ToStrin
}

class Test
{
static void Main()
{
Velocity ms = 0;
ms = 17.4;
// The statement below will perform a conversion of 9.8 to Velocity,
// then call +(Velocity, Velocity)
ms += 9.8;
}
}

(As a side-note... I don't see how this really represents a velocity, as surely that needs a direction as well as a magnitude.)

Can I overload the = assignment operator?

You can make implicit conversion in other direction string -> CharArray:

public static implicit operator CharArray(string s)
{
return new CharArray(s.Length){ Value = s };
}

Then this works:

CharArray field = new CharArray(10);
field = "Test"; // all good!
string fieldAsString = field;

Why can '=' not be overloaded in C#?

Memory managed languages usually work with references rather than objects. When you define a class and its members you are defining the object behavior, but when you create a variable you are working with references to those objects.

Now, the operator = is applied to references, not objects. When you assign a reference to another you are actually making the receiving reference point to the same object that the other reference is.

Type var1 = new Type();
Type var2 = new Type();

var2 = var1;

In the code above, two objects are created on the heap, one referred by var1 and the other by var2. Now the last statement makes the var2 reference point to the same object that var1 is referring. After that line, the garbage collector can free the second object and there is only one object in memory. In the whole process, no operation is applied to the objects themselves.

Going back to why = cannot be overloaded, the system implementation is the only sensible thing you can do with references. You can overload operations that are applied to the objects, but not to references.

Assignment operator in C#

You can always assign a variable of a given type to another variable of that type.

In other words, writing:

public void Reassign(T source)
{
Content = source;
}

will always work. You do have to deal with many types being reference types so all that is assigned is the reference. If you want to force value copying you would need to add some generic type constraints (ICloneable or similar would work, but you would then need wrappers for the common .NET types).

In other words, if you did:

public class Node<T> where T : ICloneable

You could then write

public void Assign(T source)
{
Content = source.Clone();
}

Or if you don't need to recursively value-copy there is always Object.MemberwiseClone:

public void Assign(T source)
{
Content = source.MemberwiseClone();
}

Also, in case you are not aware, .NET already has a doubly linked list in the LinkedList<T> class.

Is it possible to override assignment = in C#

No, this is not possible. The assignment operator is not overridable and for good reason.

Developers are, even within the confines of C# and modern object-oriented programming languages, often "abusing" the system to make it do things it's not supposed to do. If you could assign a different meaning than passing a reference value to a variable to an assignment operator, think of the chaos that would create when inexperienced developers use it.

What you can do is to provide methods that allow your object to take its values from a string, like so:

afoo.TakeValuesFrom("Some string value");

or

MyThingy afoo = MyThingy.FromString("Some string value");

which would be almost identical to what you are asking, and perfectly legal and readable.

Is there a workaround for overloading the assignment operator in C#?

It's still not at all clear to me that you really need this. Either:

  • Your Number type should be a struct (which is probable - numbers are the most common example of structs). Note that all the types you want your type to act like (int, decimal etc) are structs.

or:

  • Your Number type should be immutable, making every mutation operation return a new instance, in which case you don't need the data to be copied on assignment anyway. (In fact, your type should be immutable whether or not it's a struct. Mutable structs are evil, and a number certainly shouldn't be a mutable reference type.)

Overload = operator in c#

In C# you can't override the assign operator (=).

What you can do is defines implicit conversions:

class Foo
{
public Foo(int value)
{
this.Value = value;
}
public int Value { get; private set; }

public static implicit operator Foo(int value)
{
return new Foo(value);
}
}

This allows you implicitly convert from int to Foo:

Foo f = 5;

Here is a list of overloadable Operators in C#.

Overload = operator in c#

In C# you can't override the assign operator (=).

What you can do is defines implicit conversions:

class Foo
{
public Foo(int value)
{
this.Value = value;
}
public int Value { get; private set; }

public static implicit operator Foo(int value)
{
return new Foo(value);
}
}

This allows you implicitly convert from int to Foo:

Foo f = 5;

Here is a list of overloadable Operators in C#.



Related Topics



Leave a reply



Submit