Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Extension Method for Object

Is it a good idea to use an extension method on the Object class?

I was wondering if by registering this method if you were incurring a performance penalty as it would be loaded on every object that was loaded in the context.

like image 473
Mandrake Avatar asked Feb 04 '11 18:02

Mandrake


2 Answers

In addition to another answers:

there would be no performance penalty because extension methods is compiler feature. Consider following code:

public static class MyExtensions {     public static void MyMethod(this object) { ... } }   object obj = new object(); obj.MyMethod(); 

The call to MyMethod will be actually compiled to:

MyExtensions.MyMethod(obj); 
like image 127
Andrew Bezzub Avatar answered Oct 02 '22 15:10

Andrew Bezzub


There will be no performance penalty as it doesn't attach to every type in the system, it's just available to be called on any type in the system. All that will happen is that the method will show on every single object in intellisense.

The question is: do you really need it to be on object, or can it be more specific. If it needs to be on object, the make it for object.

like image 30
Darren Kopp Avatar answered Oct 02 '22 15:10

Darren Kopp