Wednesday, November 21, 2007

SOLVED - Multi-Target .Net 2.0 or Extension Methods

Update:Corrected "System.ComponentModel.CompilerServices" to "System.Runtime.CompilerServices"

Ok so it looks like "I was wrong". (well it's not like that hasn't happened before :))

NOTE: This information was found in an article called Basic Instincts in the November Edition of MSDN Magazine in a subsection entitled "Extension Methods in .NET Framework 2.0 Apps"

It's true that a .Net 2.0 targeted application cannot reference System.Core (The DLL that contains the Extension Attribute) but it turns out that you don't need to do this anyway.

Instead, you can create your own.

Yup with the following code.....
Namespace System.Runtime.CompilerServices
    Public Class ExtensionAttribute
        Inherits Attribute
    End Class
End Namespace
------------------------------------------------------------- addition to the required import where necessary...
Imports System.Runtime.CompilerServices
------------------------------------------------------------- too can fake out the IDE and have it compile your own String.ShowAsMessage Sub thus:
Public Module Ext
    <Extension()> _
    Public Sub ShowAsMessage(ByVal SomeString As String)
    End Sub
End Module
... and now you can do strange stuff like....
Call "Fred".ShowAsMessage()

The article further notes...

...this technique will not work for ASP.NET applications targeting the .NET Framework 2.0 because they have a runtime dependency on the 2.0 command-line compiler. When those apps are deployed to Web servers that only have the .NET Framework 2.0 installed, they will not work because the 2.0 VBC.EXE command-line compiler does not understand extension methods.

So I guess we just have to be careful.

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.