Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using extension methods in .NET 2.0?

I want to do this, but getting this error:

Error 1 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? [snipped some path stuff]

I have seen some answers here that says, you have to define this attribute yourself.

How do I do that?

EDIT: This is what I have:

[AttributeUsage ( AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method )] public sealed class ExtensionAttribute : Attribute {     public static int MeasureDisplayStringWidth ( this Graphics graphics, string text )     {      } } 
like image 502
Joan Venge Avatar asked Oct 05 '09 21:10

Joan Venge


People also ask

Should I use extension methods C#?

Extension methods are an excellent addition to the C# language. They enable us to write nicer, more readable code. They allow for more functionally styled programming, which is very much needed in an object-oriented language. They also should be used with care.

How do you call an extension method?

To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.

Where do you put extension methods?

An Extension Method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement. You can give any name of for the class that has an Extension Method but the class should be static.

Why might you want to use an extension method in C#?

The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.


1 Answers

Like so:

// 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 )     {            /* ... */     } } 

Alternatively; just add a reference to LINQBridge.

like image 187
Marc Gravell Avatar answered Oct 14 '22 19:10

Marc Gravell