Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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";
like image 209
ChrisBD Avatar asked Sep 13 '13 08:09

ChrisBD


People also ask

Can you override operators in C?

C does not support overloading of operators or functions. There's no way you can redefine < , <= , > , >= , == , or != to compare struct types directly.

How do you overload an assignment operator?

Overloading the assignment operator (operator=) is fairly straightforward, with one specific caveat that we'll get to. The assignment operator must be overloaded as a member function. This will call f1. operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves.

Can we override operator in C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function.

Why should we always return copy assignment operator?

If you return a reference, minimal work is done. The values from one object are copied to another object. However, if you return by value for operator= , you will call a constructor AND destructor EACH time that the assignment operator is called!!


2 Answers

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

like image 152
rpeshkov Avatar answered Oct 01 '22 09:10

rpeshkov


You can't overload the = operator as stated here

See this page for a complete list of overridable operators.

like image 24
Marshall777 Avatar answered Oct 01 '22 09:10

Marshall777