0

In C#, I'm wrapping primitive types to track what the primitive represents. Here's an example:

class Meters {
    public readonly float Value;
    public Meters(float v) { Value = v; }
}

I then compose these types into objects:

class Box {
    public Meters Width { get; set; }
    public Meters Height { get; set; }
}

Using Json.net, I need to deserialize a Box from json data that look like this:

{
    "Width": 3.23,
    "Height": 2.0
}

Can this be done without changing the json to "Width": { "Value": 3.23 } and without repeated, boilerplate code for every type like Meters?

Thanks.

1 Answer 1

5

This could be achieved by adding some implicit operator to the class that can convert a primitive (ie float, decimal, double etc) to your object. Such as.

class Meters
{

    public static implicit operator Meters(float value)
    {
        return new Meters(value);
    }

    public static implicit operator Meters(decimal value)
    {
        return new Meters((float)value);
    }

    public static implicit operator Meters(double value)
    {
        return new Meters((float)value);
    }

    public readonly float Value;

    public Meters(float v) { Value = v; }

    public override string ToString()
    {
        return Value.ToString();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.