Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dynamic extension method in C#?

Tags:

c#

.net-4.0

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'  
like image 637
serge Avatar asked Apr 20 '15 09:04

serge


2 Answers

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.

like image 110
xanatos Avatar answered Oct 06 '22 01:10

xanatos


All classes derived by object class. Maybe try this code

public static bool IsDynamicNull(this object obj)
{
    return (obj == null || obj is DynamicNull);
}
like image 31
Jacek Avatar answered Oct 06 '22 01:10

Jacek