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.
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.
If you truly intend to extend every object, then doing so is the right thing to do. However, if your extension really only applies to a subset of objects, it should be applied to the highest hierarchical level that is necessary, but no more.
Also, the method will only be available where your namespace is imported.
I have extended
Object
for a method that attempts to cast to a specified type:I also overloaded it to take in a
success
bool (likeTryParse
does):I have since expanded this to also attempt to parse
input
(by usingToString
and using a converter), but that gets more complicated.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.
This is an old question but I don't see any answers here that try to reuse the existing find function for objects that are active. Here's a succinct extension method with an optional overload for finding inactive objects.
If you use this function within the Update method you might consider changing the LINQ statement with an array for loop traversal to eliminate garbage generation.
In addition to another answers:
there would be no performance penalty because extension methods is compiler feature. Consider following code:
The call to
MyMethod
will be actually compiled to:The following example demonstrates the extension method in use.
The following example demonstrates how this method can be used.
Yes, there are cases where it is a great idea in fact.Tthere is no performance penalty whatsoever by using an extension method on the Object class. As long as you don't call this method the performance of your application won't be affected at all.
For example consider the following extension method which lists all properties of a given object and converts it to a dictionary: