serge
serge

Reputation: 15229

Creating a dynamic extension method in C#?

Is it possible to workaround this error:

public static class LayoutExtensions
{
    /// <summary>
    /// Verifies if an object is DynamicNull or just has a null value.
    /// </summary>
    public static bool IsDynamicNull(this dynamic obj)
    {
        return (obj == null || obj is DynamicNull);
    }

Compile time

Error: The first parameter of an extension method 
       cannot be of type 'dynamic'  

Upvotes: 6

Views: 5751

Answers (2)

xanatos
xanatos

Reputation: 111840

No. See https://stackoverflow.com/a/5311527/613130

When you use a dynamic object, you can't call an extension method through the "extension method syntax". To make it clear:

int[] arr = new int[5];
int first1 = arr.First(); // extension method syntax, OK
int first2 = Enumerable.First(arr); // plain syntax, OK

Both of these are ok, but with dynamic

dynamic arr = new int[5];
int first1 = arr.First(); // BOOM!
int first2 = Enumerable.First(arr); // plain syntax, OK

This is logical if you know how dynamic objects work. A dynamic variable/field/... is just an object variable/field/... (plus an attribute) that the C# compiler knows that should be treated as dynamic. And what does "treating as dynamic" means? It means that generated code, instead of using directly the variable, uses reflection to search for required methods/properties/... inside the type of the object (so in this case, inside the int[] type). Clearly reflection can't go around all the loaded assemblies to look for extension methods that could be anywhere.

Upvotes: 5

Jacek
Jacek

Reputation: 12053

All classes derived by object class. Maybe try this code

public static bool IsDynamicNull(this object obj)
{
    return (obj == null || obj is DynamicNull);
}

Upvotes: 1

Related Questions