Jako.Tako Jako.Tako - 2 months ago 8
C# Question

Weird dynamic type parameter issue

Simple code:

class Program
{
static void Main(string[] args)
{
dynamic income = "test";
var result = Test(income); // Why dynamic?
Test2(result); // WTF?
}

static string Test(string income)
{
return income;
}

static string Test2(int income)
{
return income.ToString();
}
}


The above code compiles with no errors and executes with an exception at runtime:
An unhandled exception of type Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll


Can anyone explain why
result
is determined as
dynamic
type?

Answer

When you pass a dynamic value to an expression, that entire expression becomes dynamic.

The whole point of dynamic is to turn off all type-checking; the compiler will always assume dynamic, even if the code is obviously wrong.