Wednesday, March 9, 2011

Enable Compiler Extensions in .NET 2.0

If you get an error like shown below; this is probably due to the downgrade of a project from .NET 3.5 or higher to .NET 2.0

Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll?

Extension methods are a new feature in .NET 3.5 (C#3/VB9) that let you appear to "spot weld" new methods on to existing classes.
If you think that the "string" object needs a new method, you can just add it and call it on instance variables.

But how do we accomplish this in .NET 2.0?

VB.NET

' you need this once (only), and it must be in this namespace
Namespace System.Runtime.CompilerServices
    <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Class] Or AttributeTargets.Method)> _
    Public NotInheritable Class ExtensionAttribute
        Inherits Attribute
    End Class
End Namespace
' you can have as many of these as you like, in any namespaces
Public NotInheritable Class MyExtensionMethods
    Private Sub New()
    End Sub
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function MeasureDisplayStringWidth(graphics As Graphics, text As String) As Integer
        ' ... 
 
    End Function
End Class

C#



// you need this once (only), and it must be in this namespace
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
         | AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute {}
}
// you can have as many of these as you like, in any namespaces
public static class MyExtensionMethods {
    public static int MeasureDisplayStringWidth (
            this Graphics graphics, string text )
    {
           /* ... */
    }
}

No comments:

Post a Comment