Given this short example 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();
}
When run, it will produce an exception similar to:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''object' does not contain a definition for 'Count''
Meaning compiler chose dynamic
as a preferred type of chars
variable.
Is there any reason for it not to choose IEnumerable<char>
as a concrete type, considering dynamic is not returned from Chars
method? Just changing the type manually to IEnumerable<char>
solves the issue, but I'm wondering why is dynamic
a default value in this case?
Edit
I've probably used example which was more complex than necessary. It seems that the question asked here:
Anomaly when using 'var' and 'dynamic'
Provides more concise example and some insights as to why it works the way it does.
https://blogs.msdn.microsoft.com/ericlippert/2012/11/05/dynamic-contagion-part-one/
Describes how compiler handles dynamics.