Home > Software engineering >  Is it possible to make an object which represents degrees in c#?
Is it possible to make an object which represents degrees in c#?

Time:05-28

Is it possible to have a class or struct which contains a float value which can only be between 0 and 359.999... where if you increment it past its max value it resets to 0 or a positive value below 360 when decrementing past 0.

When implemented, it would look something like this:

Degrees angle = 359;
angle  = 2;
Console.WriteLine(angle);

Output:

1

Or when decrementing below 0:

Degrees angle = 0;
angle -= 2;
Console.WriteLine(angle);

Output:

358

It would also need to be able to increment/decrement values above 360f so adding 361.5 to 0 would output 1.5

CodePudding user response:

With a combination of operator overloading and implicit keywords, it's pretty easy to do:

public readonly struct Degrees
{
    private readonly float _value;

    public Degrees(float value)
    {
        _value = value < 0
            ? 360 - (Math.Abs(value) % 360)
            : value % 360;
    }

    public override string ToString() 
        => _value.ToString();

    public static implicit operator Degrees(float f) 
        => new Degrees(f);

    public static Degrees operator  (Degrees a, Degrees b) 
        => new Degrees(a._value   b._value);
    public static Degrees operator -(Degrees a, Degrees b) 
        => new Degrees(a._value - b._value);
}

Now you can write this:

Degrees angle = 359f;
angle  = 2f;
Console.WriteLine(angle);

Which will output:

1

Or this:

Degrees angle = 0;
angle -= 2;
Console.WriteLine(angle);

CodePudding user response:

You can create strct like

public struct Degrees
{
   private decimal _angle;

   public decimal angle
   {
       get { return _angle; }
       set { _angle = value % 360; }
   }
}

And then use it as

Degrees degrees = new Degrees();
degrees.angle = 361.5m   0m;
  • Related