Extension method and dynamic object

C#DynamicC# 4.0

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

To expand on Stecya's answer... extension methods aren't supported by dynamic typing in the form of extension methods, i.e. called as if they were instance methods. However, this will work:

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

Of course, that may or may not be useful. If you could give more information about why and how you're trying to use dynamic typing, we may be able to help more.

Solution 3 - C#

Because First() is not a method of List. It is defined in Linq Extension to IEnumerable<>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsantosh singhView Question on Stackoverflow
Solution 1 - C#Eric LippertView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#StecyaView Answer on Stackoverflow