I have a short-expression that returns an int value and I'm trying to call the extension method on the result value, but when any dynamic variable is present in inner expressions, the dynamic binder is used and I receive an exception Microsoft.CSharp.RuntimeBinder.RuntimeBinderException with the message that
'int' does not contain a definition for 'AsStringOrNull'
Here is all code that reproduces the issue:
using System;
namespace ExtensionMethodsAndDynamic
{
static class Extensions
{
public static string AsStringOrNull(this object value) => value?.ToString();
}
class Program
{
public static object Foo(object value) => value;
static int GetIntFrom(object anything) => 1;
static void Main()
{
dynamic dynamicVariable = null;
string result1 = GetIntFrom((object)dynamicVariable).AsStringOrNull();// Works as expected
string result2 = GetIntFrom(dynamicVariable).AsStringOrNull();
string result3 = GetIntFrom(Foo(dynamicVariable)).AsStringOrNull();
}
}
}
Also, I noticed another behavior I can not understand.
The function is successfully called with a strictly typed argument
The same doesn't work for a dynamic argument
But it will work if we specify the function
Please help me to understand why the stuff related to dynamic variables spreads outside the call of this function int GetIntFrom(object anything).