How can I overload operator "=" in C#?

  • Thread starter Thread starter Robin.Liu
  • Start date Start date
R

Robin.Liu

Hello all!

I create a class A, and I want to insert an integer
into the object of class A directly. Like this
A a = new A();
a = 1;

The compiler doesn't allow me to overload the
operaotr "=". How can I do that?

thanks,

Robin.Liu
 
Robin.Liu said:
I create a class A, and I want to insert an integer
into the object of class A directly. Like this
A a = new A();
a = 1;

The compiler doesn't allow me to overload the
operaotr "=". How can I do that?

You can't overload the "=" operator, but you *can* include an implicit
conversion from int to A.

Personally I'd think very carefully before doing such a thing - I'm not
a fan of implicit conversions by and large - but that's the nearest
you'll get. Note that it should return a new instance of A though, it
wouldn't modify the original object as your description and sample
suggest. For that, you should have a method - something which would end
up being rather more clear anyway, IMO.
 
Robin.Liu said:
Hello all!

I create a class A, and I want to insert an integer
into the object of class A directly. Like this
A a = new A();
a = 1;

The compiler doesn't allow me to overload the
operaotr "=". How can I do that?

I'm surprised you want to. It seems rather odd practice to assign a
constant to an object reference :)
 
To echo what Jon said, you should only be doing this if your class is
representing something mathematical like int - something like Bigint, or
Complex.

Otherwise, you'll just be writing confusing code.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top