Overloading assignment operator in C#
Solution 1:
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.)
Solution 2:
You can create implicit conversion operators. There is a page on MSDN with a nice example.
It's also a good idea to make them immutable structs. That's exactly what the "primitives" are, and that's what makes it impossible to inherit from them. You want a struct because you want value-type semantics, instead of reference type semantics. And you want them immutable because mutable value types are generally a bad idea.