Is there any practical difference between these two extension methods?
class Extensions
{
public static void Foo<T>(this T obj) where T : class { ... }
public static void Foo(this object obj) { ... }
}
I was poking around in Extension Overflow and I came across the first form, which I haven't used before. Curious what the difference is.
The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.
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.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
Extension methods on Object
will also apply to value types. (And they'll be boxed by the call, reducing performance)
Extension methods on <T>
but without where T : class
will also work on value types, but will not box them.
In addition, extension methods on <T>
can write typeof(T)
to get the compile-time type of their invocation.
If you do that, note the difference between
someButton.Extension();
someButton.Extension<Control>();
someButton.Extension<Object>();
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