Extension methods with .NET Micro Framework (English)

by Marco Minerva (translated from Italian by Mike Dodaro)

The .NET Micro Framework does not support extension methods, because it does not contain the ExtensionAttribute class, which indicates that a method is an extension.  But, adding this functionality is very simple.  First, create this class in the project:

using System;

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly |
		AttributeTargets.Class |
		AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute
    { }
}

This allows creation of extension methods in the usual way:

public static class Utils
{
    public static bool StartsWith(this string s, string value)
    {
        return s.IndexOf(value) == 0;
    }

    public static bool Contains(this string s, string value)
    {
        return s.IndexOf(value) > 0;
    }
}

Use the extension as follows:

string nome = "Marco";
bool b1 = nome.StartsWith("M");	// Returns true.
bool b2 = nome.Contains("f");	// Returns false.

  1. #1 by Thierry Lecoeur on June 1, 2012 - 8:57 AM

    Thank you for code and the blog.

Leave a comment