39

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.

Mandrake
  • 1,161
  • 1
  • 10
  • 11
  • 3
    There is no performance penalty, but you do pollute the intellisense choices that come up on every symbol... Too late in the project to refactor for me, I would not do this again had I to make the choice again. – Gabriel Magana Feb 04 '11 at 18:19

6 Answers6

42

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);
Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
  • Thanks, the fact that it is a compiler feature is good to know. The other points in this thread that talk about the specificity of the scope for implementing the method are also quite good points. – Mandrake Feb 04 '11 at 19:11
15

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.

Darren Kopp
  • 76,581
  • 9
  • 79
  • 93
  • 7
    It's good to note that it will only show on "every single object in intellisense" if you've included a using statement to the namespace that your extension method has been declared within. – Doctor Jones Feb 04 '11 at 18:18
6

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:

public static T TryCast<T>(this object input)
{
    bool success;
    return TryCast<T>(input, out success);
}

I also overloaded it to take in a success bool (like TryParse does):

public static T TryCast<T>(this object input, out bool success)
{
    success = true;
    if(input is T)
        return (T)input;
    success = false;
    return default(T);
}

I have since expanded this to also attempt to parse input (by using ToString and using a converter), but that gets more complicated.

Mark Avenius
  • 13,679
  • 6
  • 42
  • 50
2

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

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:

public static IDictionary<string, object> ObjectToDictionary(object instance)
{
    var dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
    if (instance != null)
    {
        foreach (var descriptor in TypeDescriptor.GetProperties(instance))
        {
            object value = descriptor.GetValue(instance);
            dictionary.Add(descriptor.Name, value);
        }
    }
    return dictionary;
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

The following example demonstrates the extension method in use.

namespace NamespaceName
{
public static class CommonUtil
{
    public static string ListToString(this IList list)
    {
        StringBuilder result = new StringBuilder("");

        if (list.Count > 0)
        {
            result.Append(list[0].ToString());
            for (int i = 1; i < list.Count; i++)
                result.AppendFormat(", {0}", list[i].ToString());
        }
        return result.ToString();
    }
  }
}

The following example demonstrates how this method can be used.

var _list = DataContextORM.ExecuteQuery<string>("Select name from products").ToList();
string result = _list.ListToString();
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
plywoods
  • 257
  • 1
  • 3
  • 16
-1

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.

using System.Linq;

namespace UnityEngine {

public static class GameObjectExtensionMethods {

    public static GameObject Find(this GameObject gameObject, string name, 
        bool inactive = false) {

       if (inactive)
          return Resources.FindObjectsOfTypeAll<GameObject>().Where(
             a => a.name == name).FirstOrDefault();
       else
           return GameObject.Find(name);
    }
  }
}

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.

Shaun
  • 195
  • 2
  • 12