I would like to create a class type that seems to be a double value but adds some functionality to it. I know the possibility described here. But this does not allow to assign a value to an existing instance:
public interface IUnit
{
double ToScaled(double v);
double ToSI(double v);
}
public class ScalableNumber
{
public IUnit Unit { get; set; }
double val;
public double SI { get => val; set => val = value; }
public double Scaled { get => Unit?.ToScaled(val)??val; set => val = (Unit == null)? value : Unit.ToSI(value); }
public ScalableNumber(IUnit u)
{
Unit = u;
}
// implicit conversion to double, operates like an implicit get
public static implicit operator double(ScalableNumber x) => x.val;
// how do I implement an implicit set, assignig double to val
// implicit constructor from double is not useful because I lose the unit
public static implicit operator ScalableNumber(double x) => new ScalableNumber(null) { val=x};
// implicit array property is not useful because the implicit value is a single value
public double this[int i] { get => val; set => val = value; }
}
public class Unit:IUnit
{
public double scale = 1;
public double ToScaled(double v) => v/scale;
public double ToSI(double v) => scale * v;
}
public class MyExample
{
IUnit kilometer, hour, angstroemPerWeek;
public ScalableNumber way;
public ScalableNumber time;
public ScalableNumber speed;
public MyExample()
{
kilometer = new Unit() { scale = 1000 };
hour = new Unit() { scale = 3600 };
angstroemPerWeek = new Unit() { scale = 1e-10 / (60 * 60 * 24 * 7) };
way = new ScalableNumber(kilometer);
time = new ScalableNumber(hour);
speed = new ScalableNumber(angstroemPerWeek);
}
public static void ExecuteMyExample()
{
var myExample = new MyExample();
myExample.way.Scaled = 100;
myExample.time.Scaled = 1;
Console.WriteLine(myExample.Speed);
}
public void Calculate()
{
//I would like to have speed in Ångström per week.
//What I get with the present implementation is the speed in meters per second (unscaled)
speed = way / time;
}
public string Speed { get { if (time <= 0) return string.Empty; Calculate(); return speed.Scaled.ToString(); } }
}
Of course, I can code in Calculate():
speed.SI = way / time;
But if I could use the assignment without the .SI, I could re-use a lot of methods that are currently programmed for properties that have the type double.
Is there a way in c# to direct an assignment to a property without adding the property name?
/
operator?speed
. Well there is no feature of C# that can achieve this syntax exactly. I can try to think of ways that you can get close to this though, but it might be considered abusing the language.