Using Extension Methods in .NET CF 2.0

Extension methods are a great addition to the C# 3.0 Language Specification as it allows you to extend a class by adding new methods and extend the class with features you desire.  For the .NET Compact Framework developer this is available in Visual Studio 2008 and .NET Compact Framework 3.5

At OpenNETCF we have a few developer products but are still using .NETCF 2.0.  Even a lot of our consulting jobs still use .NETCF 2.0 (and sometimes 1.0) but more customers are now wanting CF3.5.

Getting used to extension methods and then not being able to use them in pre .NETCF3.5 projects is not fun.  After doing a little search I found this were Daniel explains using extension methods in .NET 2.0 and how the compiler “figures things out”. Basically the same thing applies for .NETCF 2.0.  You do require Visual Studio 2008 for this to work.

Basically what you have to do is add the following to your project:

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute
    {
    }
}

With that you can share extension methods you have written for .NETCF3.5 projects with .NETCF2.0 projects.

For example, I do a lot of custom drawing for controls on Windows Mobile and draw images with transparency.  Pre extension methods I would use something like this in .NETCF 2.0:

protected override void OnPaint(PaintEventArgs e)
{
    Bitmap image = new Bitmap(m_imagePath);
    ImageAttributes imageAtt = new ImageAttributes();
    Color transparentColor = image.GetPixel(0, 0);
    imageAtt.SetColorKey(transparentColor, transparentColor);
    e.Graphics.DrawImage(image, 
        new Rectangle(0,0,image.Width,image.Height), 
        0, 0, 
        image.Width, image.Height, 
        GraphicsUnit.Pixel, imageAtt);
    image.Dispose();
}

With the Attribute workaround above we create an extension method as follows:

public static void DrawImageTransparent(this Graphics graphics, 
    Bitmap image, 
    Rectangle destinationRect)
{
    ImageAttributes imageAtt = new ImageAttributes();
    Color transparentColor = image.GetPixel(0, 0);
    imageAtt.SetColorKey(transparentColor, transparentColor);
    graphics.DrawImage(image, 
        destinationRect, 0, 0, 
        image.Width, image.Height, 
        GraphicsUnit.Pixel, imageAtt);
}

And we can call it from our OnPaint method as follows:

using (Bitmap image = new Bitmap(m_imagePath))
    e.Graphics.DrawImageTransparent(image, new Rectangle(0, 0, image.Width, image.Height));

In the end we get a lot cleaner code and the extension method is portable to .NETCF3.5 and 2.0.


Warning: count(): Parameter must be an array or an object that implements Countable in /home/usnbis1maldq/domains/markarteaga.com/html/wp-includes/class-wp-comment-query.php on line 405

Leave a Reply