Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Method for Generic Class [duplicate]

Tags:

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)     {         // ....     } } 
like image 974
Will Avatar asked Feb 18 '10 22:02

Will


People also ask

What is extension method in MVC?

What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.

What is generic extension?

Generics are a way to tailor a class or method to a specific type. A generic method or class is designed to work for any type. This is most easily illustrated in the List<T> class, where it can be tailored to be a list of any type.

What is the extension method for a class C#?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is extension method with example?

An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.


1 Answers

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) {     //... } 
like image 164
Stan R. Avatar answered Sep 21 '22 19:09

Stan R.