29

Possible Duplicates:
C# -Generic Extension Method
How do you write a C# Extension Method for a Generically Typed Class

Is it possible to declare extension methods for generic classes?

public class NeedsExtension<T>
{
    public NeedsExtension<T> DoSomething(T obj)
    {
        // ....
    }
}
Community
  • 1
  • 1
Will
  • 609
  • 2
  • 8
  • 17

4 Answers4

64

To extend any class

public static class Extensions
{
    public static T DoSomething<T>(this T obj)
    {
        //...
    }
}

To extend a specific generic class

public static NeedExtension<T> DoSomething<T>(this NeedExtension<T> obj)
{
    //...
}
Noam M
  • 3,156
  • 5
  • 26
  • 41
Stan R.
  • 15,757
  • 4
  • 50
  • 58
  • 2
    For me I forgot the after the NeedExtension. More specifically I wanted to write an extention for the generic Dictionary class, so I needed . – Vincent Vancalbergh Oct 10 '18 at 09:48
5

Yes, but you forgot the this keyword. Look at Queryable that provides all the LINQ operators on collections.

Johannes Rudolph
  • 35,298
  • 14
  • 114
  • 172
1

Sure

public static void SomeMethod<T>(this NeedsExtension<T> value) {
  ...
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
-3

How do you write a C# Extension Method for a Generically Typed Class

public static class NeedsExtension<T>
{
    public static string DoSomething <T>(this MyType<T> v)
    {   return ""; }

    // OR
    public static void DoSomething <T>(this MyType<T> v)
    {   
         //...
    }
}
LiefdeWen
  • 586
  • 2
  • 14
Asad
  • 21,468
  • 17
  • 69
  • 94