C# TimeSpan TypeConverter and UITypeEditor

Code for this post is on GitHub.

I have an application that presents various TimeSpan properties to a user. The default string conversion isn’t great, in fact for anything other than hh:mm:ss it isn’t intuitive.

A TimeSpan of 1 day, 2 minutes, 3 hours, 4 seconds, and 5 milliseconds is shown in the example below:

Dev10.png

After a little noodling I found some articles that helped me put together something better (at least for me!).

The first feature is the presentation of a TimeSpan instance as a string:

dev10

The second feature is the ability to convert back from a string. For example, entering a value of 1h, 5s:

Dev10.png

… becomes…

Dev10.png

And finally, the property can present an interactive editor via a dropdown:

Dev10.png

Here’s an example of how the new classes are used as attributes on a TimeSpan:

[TypeConverter(typeof(TimeSpanStringConverter))]
[Editor(typeof(TimeSpanUIEditor), typeof(UITypeEditor))]
[DefaultValue(typeof(TimeSpan), "1.02:03:04.005")]
[DisplayName("Custom 1")]
public TimeSpan A { get; set; } = new TimeSpan(1, 2, 3, 4, 5);