Adding extension method support for .NET 2.0

Microsoft .NET

.NET Framework 2.0 does not support extension methods out of the box, because you cannot reference System.Core that was introduced in .NET 3.5. However, by adding a simple attribute class you can use extension methods in .NET 2.0 as well. Here is the snippet.

namespace System.Runtime.CompilerServices {
    /// <summary>
    /// Mimics the .NET 3.5 extension methods attribute
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    internal sealed class ExtensionAttribute : System.Attribute {
        /// <summary>
        /// Instantiates a new instance of the ExtensionAttribute class
        /// </summary>
        public ExtensionAttribute()
            : base() {
        }
    }
}

Here is an example afterwards using extension methods in one of our applications.

namespace Setup.AppCode {
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Text;
    using System.Runtime.CompilerServices;

    /// <summary>
    /// Extension methods class
    /// </summary>
    public static class ExtensionMethods {

        public static void DisableAllLinks(this LinkLabel control) {
            foreach (LinkLabel.Link link in control.Links) {
                link.Enabled = false;
            }
        }

        public static void EnableAllLinks(this LinkLabel control) {
            foreach (LinkLabel.Link link in control.Links) {
                link.Enabled = true;
            }
        }

    }
}

And don’t forget to import the namespace that contains your extension methods where you will need them so they appear correctly.

Leave a Comment

Your email address will not be published. Required fields are marked *