'Is it possible to override assignment "=" in C# [duplicate]

I have a complex object type for which I'm overriding the "base.ToString()" method so that it returns a string property value.

for example:

class foo
{
 public string StringValue{get;set;}
 public int SomeOtherValue{ get;set;}
 public override ToString()
 {
   return StringValue;
 }
}

So this allows me to use retrieve the value of the StringValue property easily.

Is there a way in which I can override or extend the base functionality so that I can use simple code such as below to set the StringValue property?

foo aFoo = new foo();
aFoo = "Some string value";


Solution 1:[1]

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.

Solution 2:[2]

You can use implicit cast operator overload: http://msdn.microsoft.com/library/z5z9kes2.aspx

Solution 3:[3]

You can't overload the = operator as stated here

See this page for a complete list of overridable operators.

Solution 4:[4]

No you cannot. It is a protected part of the C# language specification. Being able to override this would be like overriding your bodies ability to breathe air with breathing water.

Solution 5:[5]

Use implicit conversion operators. It will do exactly what you need

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roy Dictus
Solution 2 rpeshkov
Solution 3 Marshall777
Solution 4 BenM
Solution 5 Ehab Kashkash