Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any practical difference between an extension method on <T> or on Object?

Tags:

c#

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.

like image 440
scobi Avatar asked Jun 03 '10 21:06

scobi


People also ask

What is the difference between a static method and an extension method?

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.

What is the main purpose of an extension method?

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 an advantage of using extension methods?

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.


1 Answers

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>();
like image 161
SLaks Avatar answered Nov 03 '22 00:11

SLaks