I actually put this together a while ago but have just realised I never put it up here.
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.
.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.
var interval = TimeSpan.FromHours(10); var seconds = interval.TotalSeconds; // 36000
I thought this would be useful for distances as well, so put together a helper library.
A .NET object to handle distance.
So you can do things like this:
var distance = Distance.FromMeters(100); var miles = distance.ToMiles(); var leagues = distance.ToLeagues();
Supports operators as well:
var distance1 = Distance.FromYards(300); var distance2 = Distance.FromThou(1000); var totalMeters = (distance1 + distance2).ToMeters();
So, there you go. Use, hack, fork, whatever.