New type definition in C#

c#, types

Solution

A type may be overkill, but if you want one, this is a good start:

struct Double180 : IEquatable<Double180>
{
    private readonly double value;

    public Double180(double d)
    {
        if (d < -180 || d > 180)
        {
            throw new ArgumentOutOfRangeException("d");
        }

        this.value = d;
    }

    public static implicit operator double(Double180 d)
    {
        return d.value;
    }

    public static explicit operator Double180(double d)
    {
        return new Double180(d);
    }

    public override string ToString()
    {
        return this.value.ToString();
    }

    public bool Equals(Double180 other)
    {
        return this.value == other.value;
    }

    public override bool Equals(object obj)
    {
        return obj is Double180 && this.Equals((Double180)obj);
    }

    public override int GetHashCode()
    {
        return this.value.GetHashCode();
    }

    public static bool operator ==(Double180 a, Double180 b)
    {
        return a.Equals(b);
    }

    public static bool operator !=(Double180 a, Double180 b)
    {
        return !a.Equals(b);
    }
}

Of course, there are many more interfaces to implement, for example `IConvertible` and `IComparable<Double180>` would be nice.

As you can see, you know where this starts, but you don't know where it ends.

A setter validator, as suggested by the other answers, might be a better idea.

Problem

I am looking for possibilities to define a new type and using it in C# like below: Class definition: ``` public class Position { public double180 Longitude { get; set; } // double180 is a type within a range -180 and 180 public double90 Latitude { get; set; } // double90 is a type within a range of -90 and 90 } ``` Usage: ``` var position = new Position { Longitude = 45, Latitude = 96 // This line should give an error while initializing the object }; ```

Original source