Mandrake
Mandrake

Reputation: 1161

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.

Upvotes: 39

Views: 35799

Answers (5)

plywoods
plywoods

Reputation: 257

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();

Upvotes: 0

Mark Avenius
Mark Avenius

Reputation: 13957

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.

Upvotes: 7

Andrew Bezzub
Andrew Bezzub

Reputation: 16032

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);

Upvotes: 42

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

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;
}

Upvotes: 2

Darren Kopp
Darren Kopp

Reputation: 77697

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.

Upvotes: 15

Related Questions