Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method and dynamic object

Tags:

c#

dynamic

c#-4.0

I am going to summarize my problem into the following code snippet.

List<int> list = new List<int>() { 5, 56, 2, 4, 63, 2 }; Console.WriteLine(list.First()); 

Above code is working fine.

Now I tried the following

dynamic dList = list;  Console.WriteLine(dList.First()); 

but I am getting RuntimeBinderException.Why is it so?

like image 750
santosh singh Avatar asked Mar 15 '11 12:03

santosh singh


People also ask

What is meant by extension method?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

Can we call a method from an extension on dynamic types?

We can not call the Extension method on the dynamic type.

What is extension method in MVC?

What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.

What is the difference between a static method and an extension method?

The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.


1 Answers

To expand on Jon's answer, the reason this doesn't work is because in regular, non-dynamic code extension methods work by doing a full search of all the classes known to the compiler for a static class that has an extension method that matches. The search goes in order based on the namespace nesting and available using directives in each namespace.

That means that in order to get a dynamic extension method invocation resolved correctly, somehow the DLR has to know at runtime what all the namespace nestings and using directives were in your source code. We do not have a mechanism handy for encoding all that information into the call site. We considered inventing such a mechanism, but decided that it was too high cost and produced too much schedule risk to be worth it.

like image 125
Eric Lippert Avatar answered Sep 19 '22 07:09

Eric Lippert