Search code examples
c#extension-methodsobject-type

Using Extension Methods on Underlying Type Contained by an 'object' at Runtime


I asked a question recently on the same project I'm working on, but this is a specific question regarding extension methods and the object type.

The following code doesn't work:

object ProcessField(byte [] buff, int position, Dictionary<int, Type> fields)
{
    int field = buff[position];
    position++;

    // Create an instance of the specified type.
    object value = Activator.CreateInstance(fields[field]);
    // Call an extension method for the specified type.
    value.DoSomething();

    return value;
}

public static void DoSomething(this Int32 value)
{
    // Do Something
}

public static void DoSomething(this Int16 value)
{
    // Do something...
}

The compiler gives this error:

'object' does not contain a definition for 'DoSomething' and the best extension method overload 'DoSomething()' has some invalid arguments in blah blah...

It seems the extension method isn't bound at runtime, even though the underlying type is System.Int32 or System.Int16 (verified at runtime).

Is there any way to make this work (using extension methods)? Is it just code semantics, or is it just not possible on an 'object' without casting it at design time?


Solution

  • This is ...uhhh... really bad, but you can achieve what you want like this using dynamic. But don't do it. It's really bad.

    object ProcessField(byte [] buff, int position, Dictionary<int, Type> fields)
    {
        int field = buff[position];
        position++;  // this line really does absolutely nothing
    
        // dynamic is magic!
        dynamic value = Activator.CreateInstance(fields[field]);
    
        DoSomething(value);
    
        return value;
    }