In my spare time, I've been working on a Silverlight sample that can be used to browse the wallpaper on my main web site.
As part of that, I have been implementing a custom panel with layout/positioning code. Since all coordinates in Silverlight are double values, you can sometimes get stuck in situations where you need to treat 1.0000001 and 1.00001 as the same value. Rather than implement a helper class or a base class (both of which are things I typically do), I decided to try an extension method and make it available any place there is a double value in my code.
(Silverlight hosts a version of the .NET 3.5 framework, so this information will generally apply to both windows CLR and agclr applications. )
Creating an extension method is pretty simple. Just define a static class with a static method.
public static class Extensions
// extends the double class to tell us if something is within
// a reasonable tolerance of the indicated value.
public static bool WithinToleranceOf(this double d1, double d2)
return WithinToleranceOf(d1, d2, 0.001);
public static bool WithinToleranceOf(this double d1, double d2, double tolerance)
return Math.Abs(d1 - d2) < tolerance;
Now any place in my code where I have a double value, and am using the namespace within which the Extensions class exists, the double is extended with the WithinToleranceOf method. Intellisense for the double type shows:
It reminds me of some of the earlier C and C++ code, or at least the C code some early C++ compilers generated in that the first parameter to the function is a reference to the type you are attaching to.
Operator overloading is also an approach to this problem, but as of the last time I checked, you could not overload operators via extension methods. Given that I have to get around limitations of inheritance here, I would have to go at it externally, so that would not work.
While legitimate arguments against the purity of such an approach in an OO language can be made, there's no doubt as to its usefulness in real-world applications.