Overloading an assignment operator in C #

I know that the = operator cannot be overloaded, but there must be a way to do what I want here:

I just create classes to represent quantitative units, as I do a bit of physics. Apparently, I can't just inherit from the primitive, but I want my classes to behave like primitives - I just want them to type differently.

So I could go

 Velocity ms = 0; ms = 17.4; ms += 9.8; 

and etc.

I am not sure how to do this. I decided that I would just write a few of these classes:

 class Power { private Double Value { get; set; } //operator overloads for +, -, /, *, =, etc } 

But apparently, I cannot overload the assignment operator. Is there any way to get this behavior?

+42
c # operator-overloading
Dec 27 '10 at 9:44
source share
3 answers

It looks like you should use a structure, not a class ..., and then create an implicit conversion operator, as well as various operators to add, etc.

Here is a 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 speed, since it certainly requires both direction and magnitude).

+67
Dec 27 '10 at 9:51
source share

You can create implicit conversion operators. Good example: a page on MSDN .

It is also a good idea to make them immutable. That is what the "primitives" are, and what makes it impossible to inherit them. You need a structure because you want value type semantics, not a reference type semantics. And you want them to be immutable, because mutable value types are usually a bad idea.

+9
Dec 27 '10 at 9:49
source share

I think that it cannot be overloaded, because all C # classes are derived from Object, therefore they are mostly objects, and when you use assignment operators, you basically just refer to another object. On the other hand, if you use a structure, then you basically need all the information, so when you use the = operator, all fields will be copied.

So, I would say, look at it and implement the Copy () function, and you should be fine :-)

-9
Dec 27 '10 at 9:47
source share



All Articles