.NET Distance Model
I actually put this together a while ago but have just realised I never put it up here.
The Problem
As part of some of the work I’ve been doing over the past year or so, we’ve run into issues dealing with units of distance. The most problematic of these being when an app that was created for a US market had to be converted for use in a country that used the metric system. So, the variable distanceInMiles was suddenly getting a value from the database in kilometres and had to be converted on the front end.
Just a bit confusing.
About Time
.NET has a really good framework class for lengths of time – TimeSpan. This allows you to set a length of time using any unit (second, minute, hour) and then read that back as any other supported format.
For example:
I thought this would be useful for distances as well, so put together a helper library.
dotnet-distance
A .NET object to handle distance.
Full source available on GitHub. Available as a package on NuGet.
Usage
So you can do things like this:
Supports operators as well:
Supported Units
Metric
- Millimeters
- Centimeters
- Meters
- Kilometers
Imperial
- Thou
- Inches
- Feet
- Yards
- Chains
- Furlongs
- Miles
- Leagues
So, there you go. Use, hack, fork, whatever.