Physical Quantities in C#

Scientific applications usually perform lots of calculations with physical quantities. If you do not represent them properly in your code you run the risk of mixing them up. For example, it’s easy to add a value in meters to a value in kilometers if you simply work with variables of primitive types like double or decimal. It can help to encode the unit in the variable name, e.g. massInKilogram, but it’s much better to let the type system handle it.

So here’s some C# code which models a generic physical quantity and its unit:

public abstract class Quantity<T> where T : Quantity<T>, new()
    private decimal value;

    public decimal In(Unit<T> unit)
        return value / unit.Factor;

    public string ToStringIn(Unit<T> unit)
        return string.Format("{0} {1}", In(unit), unit.Text);

    public class Unit<Q> where Q : Quantity<Q>, new()
        public decimal Factor { get; private set; }
        public string Text { get; private set; }

        public Unit(string representation, decimal factor)
            Text = representation;
            Factor = factor;

        public static Q operator *(decimal value, Unit<Q> unit)
            var quantity = new Q();
            quantity.value = value * unit.Factor;
            return quantity;

With this base class we can easily implement some quantities:

class Duration : Quantity<Duration>
    public static readonly Unit<Duration> Millisecond = new Unit<Duration>("ms", 1e-3M);
    public static readonly Unit<Duration> Second = new Unit<Duration>("s", 1M);
    public static readonly Unit<Duration> Minute = new Unit<Duration>("min", 60M);

class Mass : Quantity<Mass>
    public static readonly Unit<Mass> Milligram = new Unit<Mass>("mg", 1e-3M);
    public static readonly Unit<Mass> Gram = new Unit<Mass>("g", 1M);
    public static readonly Unit<Mass> Kilogram = new Unit<Mass>("kg", 1e+3M);

And this is how they are used:

var t = 30 * Duration.Second;

var m = 10 * Mass.Gram;

The Unit class uses operator overloading to overload the multiplication operator. Instead of calling a constructor directly we use multiplication with a unit to create new instances of a quantity.

The type system prevents nonsense like this:

// does not compile
(10 * Mass.Gram).In(Duration.Minute);

You will probably want to overload more operators of the quantity classes depending on your use case. You can also overload operators to produce instances of new quantities:

Velocity v = (3.5 * Length.Kilometer) / (10 * Duration.Minute);

class Velocity : Quantity
    public static readonly Unit MeterPerSecond = new Unit("m/s", 1M);

class Length : Quantity
    public static readonly Unit Meter = new Unit("m", 1M);
    public static readonly Unit Kilometer = new Unit("m", 1e+3M);

    public static Velocity operator /(Length s, Duration t)
        return (s.In(Length.Meter) / t.In(Duration.Second)) * Velocity.MeterPerSecond;

If you do not want to hand craft your quantities you might want to check out existing libraries for working with quantities like QuantityTypes.

One thought on “Physical Quantities in C#

  1. Pingback: Quantities in C++ and User Defined Literals | Schneide Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.