Main Site Documentation

Extension Methods to the rescue


#1

When I was playing with the multi-color LEDs on my Spider I was at first a bit annoyed that GHI chose to use the TimeSpan class to represent a time delay for blinking the LED. I was thinking, “why not just use an int to represent milliseconds or something”. Then it occurred to me that by using TimeSpan they made the argument unambiguous.

How many times have you seen an API with a method like this:

void foo(int time)

Then you are left wondering what units of time they are expecting, milliseconds, seconds, eons? By using a TimeSpan object our friends at GHI not only made the argument unambiguous they made a single method work instead of having overloads if we wanted to set the time in minutes or hours.

Then I got to thinking, “well I want to work with milliseconds, and I can use one of the overloaded TimeSpan constructors for that but then I wind with with rather ugly code”.

TimeSpan RedTime = new TimeSpan(0, 0, 0, 0, (int)PulseDuration);

All those zeros padding the constructor bug me as they don’t tell me anything about what those zero arguments mean. If I look at code like this a month after writing it then I have to look up the TimeSpan class in the API docs and try to figure it out, again.

It seemed a few simple Extension methods would really help out here as NETMF does not have the full implementation of the TimeSpan class (as does the full .NET). Using an extension method the code above looks like this:

TimeSpan RedTime = PulseDuration.TimeSpanFromMilliseconds();

This code is very clear. We have a value in milliseconds, stored in PulseDuration, that we are getting a TimeSpan object from. I could read this a month from now and know what it was doing without having to remember the 5 overloaded constructors of the TimeSpan class. :wink:

I thought I would add something to the Wiki about Extension methods but there was already an entry. Be sure to take a look to find out more about extension methods:

http://wiki.tinyclr.com/index.php?title=Extension_Methods#Introduction

The simple extension methods I created for the TimeSpan class can be found here:

http://code.tinyclr.com/project/390/timespan-extensionmethods/


#2

Helpful. Thanks!


#3

Maybe we can add millisecond as another option.


#4

I think using the TimeSpan, as is, was a brilliant move Gus. No need to add a millisecond blink method. The current API is nice and clean.

My point in sharing this was to make others aware that extension methods can help make your code more understandable, and they are easy to implement.