Given this short sample program:
static void Main(string[] args) { Console.WriteLine(Test("hello world")); } private static int Test(dynamic value) { var chars = Chars(value.ToString()); return chars.Count(); } private static IEnumerable<char> Chars(string str) { return str.Distinct(); }
An exception will be thrown at startup, similar to:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''object' does not contain a definition for 'Count''
The compiler value chose dynamic as the preferred type of the chars variable.
Does it have a reason not to select IEnumerable<char> as a specific type, given that the dynamic method is not returned from the chars method? Just changing the type manually to IEnumerable<char> solves the problem, but I wonder why dynamic is the default value in this case?
Edit
I probably used an example that was more complex than necessary. It seems that the question asked here:
Anomaly when using "var" and "dynamic"
Provides a shorter example and some information on why it works the way it does.
https://blogs.msdn.microsoft.com/ericlippert/2012/11/05/dynamic-contagion-part-one/
Describes how the compiler processes dynamics.
c #
Alex
source share