Compiling Extension Methods on .net 2.0 runtime

Today, I had to work on a legacy .net 2.0 application and I found a neat little trick one of developers did to get extension methods to work on .net 2.0 runtime. I was pretty amazed because I thought extension methods was a feature available in System.Core assembly that is part of .net 3.5 framework.  In reality that is completely true and Extensions are available only in .net 3.5. However extension methods gets converted into the same IL code that is compatible with .net 2.0 runtime. So the only thing left is to satisfy the Visual Studio compiler that extension methods are valid statements for .net 2.0. On asking the developer who wrote the code, he said that in Visual studio .net 2.0 compiler only checks for an attribute called System.Runtime.CompilerService.ExtensionAttribute to be available for extension methods to work. So he basically added a dummy class of that type that inherits from Attribute class. After adding the ExtensionAttribute class, the compiler was satisfied and the project build fine.

image

image

The above code does not compile because the project is targeting .net 2.0 assemblies. Once we add our dummy class called System.Runtime.CompilerService.ExtensionAttribute the project builds correctly as shown in the screen below.

image

No Comments