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) { // .... } }
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.
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.
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.
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.
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) { //... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With