Creating a dynamic extension method in C #?

Is there a way around 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); } 

Compilation time

 Error: The first parameter of an extension method cannot be of type 'dynamic' 
+5
source share
2 answers

Not. See fooobar.com/questions/37954 / ...

When you use a dynamic object, you cannot call the extension method with 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 them are fine, 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 / field / ... variable (plus an attribute), which the C # compiler knows should be considered dynamic . And what does "treatment as dynamic" mean? This means that the generated code, instead of using the variable directly, uses reflection to search for the necessary methods / properties / ... inside the type of the object (therefore, in this case, inside the type int[] ). A clear reflection cannot go around all loaded assemblies in order to look for extension methods that can be anywhere.

+3
source

All classes obtained by the class of the object. Maybe try this code

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

All Articles