Adding fluent interfaces to .NET framework classes
If you are going to blog, I think it’s important to blog regularly (I say this after taking about a year off). The drawback is that you might not always have “big bang” articles. Still, I think this is kind of cool. Here’s a fluent interface that I added to System.Thread. I think this is a good example of adding a simple fluent interface to an existing .NET framework class.
For the record, I want to say that I often do experiments like this in my day to day work. I find that I am continually trying to find ways to make the code that I write more readable (within the context I am writing it).
public class ThreadWaitFor
{
private readonly Thread _thread;
private readonly int _value;
public ThreadWaitFor(Thread thread, int value)
{
_thread = thread;
_value = value;
}
public void Milliseconds()
{
_thread.Join(_value);
}
public void Seconds()
{
_thread.Join(_value * 1000);
}
public void Minutes()
{
_thread.Join((_value * 1000) * 60);
}
}
public static class ThreadExtensions
{
public static ThreadWaitFor WaitFor(this Thread thread, int value)
{
return new ThreadWaitFor(thread, value);
}
}
This allows me to do this:
Thread.CurrentThread.WaitFor(30).Seconds();
Thread.CurrentThread.WaitFor(5).Minutes();
Thread.CurrentThread.WaitFor(1000).Milliseconds();