简体   繁体   中英

Clamping and rounding a value during implicit conversion

I've developer a custom integral type. Here it is its definition in C#.

public struct PitchClass
{
    private readonly int value;

    private PitchClass(int value)
    {
        this.value = CanonicalModulus.Calculate(value, 12);
    }

    public static implicit operator PitchClass(int value)
    {
        return new PitchClass(value);
    }

    public static implicit operator PitchClass(double value)
    {
        return new PitchClass((int)Math.Round(value));
    }

    public static implicit operator int(PitchClass pitchClass)
    {
        return pitchClass.value;
    }
}

The PitchClass is an int whose values are in the range [0, 11].

As you can read from the C# code both int and double values can be implicitly converted to PitchClass using a canonical modulus operator :

PitchClass pitchClass = -3;
Console.WriteLine(pitchClass); // 9

The double value is also rounded during implicit conversion:

PitchClass pitchClass = -3.4d;
Console.WriteLine(pitchClass); // 9

I couldn't find other examples of custom data types that do so many things to the data type to convert.

Why? Is it bad practice? If so, is there another way to avoid doing argument validation for every PitchClass variable in every method?

Thanks

It is not bad practice to create a base type and make it convertible to other base data types. Neither is it to define implicit and explicit conversions.

Look at the implementation of Int32 in the .Net Framework . This structure implements many interfaces to make it Convertible to other structure types, to format it nicely and a few other stuff.

If you intend on heavily using this structure, implementing IConvertible, IComparable, IEquatable (and the methods GetHashCode() & Equals()) is a good idea, because almost all the native data types do so.

The Complex type is given as example of Custom data type in the explanation for IConvertible interface and they do many different conversions to and from other types.

Also, the explicit conversion from double to int is doing kind of the same thing you do, making this conversion narrowing (may incur data loss).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM