Extension Method for Generic Class [Duplicate]

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

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

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

Sure

public static void SomeMethod<T>(this NeedsExtension<T> value) {
  ...
}

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)
    {   
         //...
    }
}
5
Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest