-1

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?

6
  • 1
    Sounds like you need to overload the / operator?
    – Sweeper
    Jun 13, 2022 at 16:11
  • @Sweeper no, I actually need a functionality that is like an overload of the = operator for the type double to assign to a property instead of assigning a new instance.
    – SDG
    Jun 13, 2022 at 16:14
  • 1
    Ah I see, you want to preserve the unit that is originally in 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.
    – Sweeper
    Jun 13, 2022 at 16:22
  • 1
    This is precisely the reason for the rather ubiquitous convention of not using public fields, but using properties for accessing state. It gives you control over how assigned values are actually stored and how stored values are exposed to consumers. Given that you asked about properties, it even seems that you know this, and yet your code uses a field.
    – Servy
    Jun 13, 2022 at 16:52
  • @Servy I have both, a private field val and the public property accessor SI. If you have an answer to the question...
    – SDG
    Jun 14, 2022 at 6:18

1 Answer 1

1

The short answer is that you can't overload the assignment operator.

The long answer is that if you're willing to do something a bit hacky, you can kinda accomplish what you want with generics and an upcoming feature of C# 11, static abstract interface members.

Basically if you wanna keep the unit information, you will have to find somewhere else to store it, so store it in the type itself.

public interface IUnit
{
    static abstract double ToScaled(double v);
    static abstract double ToSI(double v);

}

// these interfaces exist so you can box the struct or use them as a generic constraint
public interface IScalableNumber
{
    double SI { get; set; }
    double Scaled { get; set; }
}

public interface IScalableNumber<TSelf> 
    : 
    IScalableNumber,
    IAdditionOperators<TSelf, double, TSelf>
    // more I...Operators interfaces
    where TSelf : IScalableNumber<TSelf>
{
    static abstract implicit operator TSelf(double x);
}

// changed this to struct because I didn't see a reason for it to remain a class
public struct ScalableNumber<TUnit> : IScalableNumber<ScalableNumber<TUnit>> where TUnit : IUnit
{
    private double val;

    public double SI { get => val; set => val = value; }
    public double Scaled { get => TUnit.ToScaled(val); set => TUnit.ToSI(val); }

    public static ScalableNumber<TUnit> operator +(ScalableNumber<TUnit> left, double right) => left.val + right;

    public static implicit operator double(ScalableNumber<TUnit> x) => x.val;
    public static implicit operator ScalableNumber<TUnit>(double x) => new() { val = x };

    public ScalableNumber<TNewUnit> WithDifferentUnit<TNewUnit>() where TNewUnit : IUnit => val;
}

public abstract class KilometerUnit : IUnit
{
    private const double scale = 1000;
    public static double ToScaled(double v) => v / scale;
    public static double ToSI(double v) => scale * v;
}

public abstract class HourUnit : IUnit
{
    private const double scale = 3600;
    public static double ToScaled(double v) => v / scale;
    public static double ToSI(double v) => scale * v;
}

public abstract class AngstroemPerWeekUnit : IUnit
{
    private const double scale = 1e-10 / (60 * 60 * 24 * 7);
    public static double ToScaled(double v) => v / scale;
    public static double ToSI(double v) => scale * v;
}
public class MyExample
{
    public ScalableNumber<KilometerUnit> way;
    public ScalableNumber<HourUnit> time;
    public ScalableNumber<AngstroemPerWeekUnit> speed;

    public MyExample()
    {
        way = new();
        time = new();
        speed = new();
    }
    public static void ExecuteMyExample()
    {
        var myExample = new MyExample();
        myExample.way.Scaled = 100;
        myExample.time.Scaled = 1;
        Console.WriteLine(myExample.Speed);
    }

    public void Calculate()
    {
        speed = way / time;
        //now after the assignment, speed is still in 'AngstroemPerWeek'

        // in order to change between units do this
        way = time.WithDifferentUnit<KilometerUnit>();

        // implicit assignment won't work with the non generic interface:
        IScalableNumber speedBoxed = speed;
        speedBoxed = 10.0;

        // all of these should work flawlessly though :) ... and allocate no heap memory
        IncrementScalable(ref way);
        IncrementScalable(ref time);
        IncrementScalable(ref speed);
    }

    public void IncrementScalable<TScalable>(ref TScalable someNumber) where TScalable : IScalableNumber<TScalable>
    {
        someNumber += 1;
    }
public string Speed { get { if (time <= 0) return string.Empty; Calculate(); return speed.Scaled.ToString(); } }

}

1
  • Seems that there is actually no easy solution. I have learned a lot from your answer; it is interesting, but I will probably no use it because in fact, the classes that currently implement this functionality (operating getter and setter delegates to the owning object's property of type double instead of the field val) have much more functionality than just the unit.
    – SDG
    Jun 14, 2022 at 15:52

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.