Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Extension methods in .NET 2.0

Tags:

c#

.net

I have found several links to methods of making extension methods work in .NET2.0 (The moth, Discord & Rhyme, Stack Overflow). I have also heard vaguely from a colleague that this causes some problems with libraries or something? Is this the case? Also all 3 use different methods:

The moth:

namespace System.Runtime.CompilerServices
{
  public class ExtensionAttribute : Attribute { }
}

Discord and Rhyme

namespace System.Runtime.CompilerServices
{
  [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
  public class ExtensionAttribute : Attribute {}
}

Stack Overflow

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
         | AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute {}
}

Whats the difference between these methods, and which one would you recommend?

like image 640
Casebash Avatar asked Feb 27 '23 13:02

Casebash


2 Answers

Ultimately it isn't going to make much difference; you could argue that the one that matches the runtime is preferred, but the ideal answer is to switch to .NET 3.5 (otherwise at a later date it can get confusing with different versions of the same attribute in scope etc).

The [AttributeUsage] will prevent it being attached to things where it won't do anything - but it won't do aything by itself anyway...

Looking at metadata against the type, the exact attribute usage seems most like the stackoverflow variant - but ultimately this isn't hugely important - the name and namespace is all that matters (and that it inherits from Attribute).

like image 60
Marc Gravell Avatar answered Mar 07 '23 12:03

Marc Gravell


The difference is simple enough:

In your first example, you can put the attribute anywhere. In the second example, you can only apply it to a method, never more than one to the same method and an inherited class with the method overridden will not inherit the attribute. In the third example, you can apply it to a method, a class or an assembly.

If you try to apply it in any other place, you will get a compiler error.

The second seems to make most sense.

like image 32
pdr Avatar answered Mar 07 '23 12:03

pdr