Tuesday, February 6, 2018

Add Extension method for .Net 2.0

To add extension method in a library that is build on framework 2.0 you need to add following class in your project

using System;

#pragma warning disable 1685
namespace System.Runtime.CompilerServices
    [AttributeUsage (AttributeTargets.Method | 
    AttributeTargets.Class | AttributeTargets.Assembly)]
    public sealed class ExtensionAttribute : Attribute

With this mimic System.Runtime.CompilerServices.ExtensionAttribute class in your project, its compilation will succeed even when targeting .NET 2.0.

Note: Since our mimic ExtensionAttribute collides with the one in the global assembly cache, the compiler will generate a warning CS1685. We are of course deliberately doing this. Thus, we add the line of #pragma to suppress that warning.

Source : https://www.codeproject.com/Tips/512823/Using-Extension-Methods-in-NET-SP

No comments: