Here's my code:
class Program
{
static void Main(string[] args)
{
dynamic param = null;
System.Diagnostics.Debug.Assert(whatever(param));
}
static bool whatever(object param)
{
return true;
}
}
When I run it I get RuntimeBinderException
with the following message:
Cannot dynamically invoke method 'Assert' because it has a Conditional attribute
Yes, Assert()
has ConditionalAttribute
on it. Yet there's exactly one whatever()
method that returns bool
no matter what the method accepts.
What exactly does runtime complain about? Why cannot it use the bool
and pass it into Assert()
?
The actual call in
Main
gets translated into aCallSite
, because you're invoking the call with adynamic param
. TheCallSite
does all the preparation it needs in order to invoke this method at run-time. But, the problem is, thatAssert
has aConditional
attribute on it, which means it needs to pass information to the compiler pre-processor at compile-timeThis blog post explains:
And later, to strengthen our point:
Now, we have a conflict. We can't pass parameters to the compiler pre-processor at run-time (to tell it if "DEBUG" is defined or not), only at compile-time, but the method will only be invoked at run-time, because that's when we'll infer the type of our
dynamic
value.That's why the binder yells at run-time that this method can't actually be invoked, because that would be breaking the
ConditionalAttribute
.Bonus:
This is what actually gets called: