Question

How does the is operator work with respect to the DLR?

To make my question a little more explicit, consider the following signature:

 public bool Is<T>(Func<dynamic> getInstance)
 { 
     return getInstance() is T;
 }

By default, what conditions are necessary for Is<T> to return true? Furthermore, does the DLR provide any mechanism to customize this behavior?

Was it helpful?

Solution

At runtime, dynamic is treated the same as object, which means that the runtime type of the getInstance delegate's result will be used to perform this check. The only difference using dynamic here will cause is that there will be no compile time checking, and dynamic binding will be used at runtime to perform this check on the dynamic object returned by getInstance.

By default, what conditions are necessary for Is to return true?

The delegate passed in will need to return a type which, at runtime, is compatible with T.

Furthermore, does the DLR provide any mechanism to customize this behavior?

No. This is going to use the standard rules for C# types. Any custom behavior would need to be written into the logic itself.

OTHER TIPS

Since is already is a runtime test, there is no extra runtime binding being done, in fact there won't be any compiled IL difference to

 public bool Is<T>(Func<object> getInstance)
 { 
     return getInstance() is T;
 }

The IL for the method body of both Is<T>(Func<object> getInstance) and Is<T>(Func<dynamic> getInstance):

    .maxstack 2
    .locals init (
        [0] bool CS$1$0000)
    L_0000: nop 
    L_0001: ldarg.1 
    L_0002: callvirt instance !0 [mscorlib]System.Func`1<object>::Invoke()
    L_0007: isinst !!T
    L_000c: ldnull 
    L_000d: cgt.un 
    L_000f: stloc.0 
    L_0010: br.s L_0012
    L_0012: ldloc.0 
    L_0013: ret 

So the answer is that is keyword is not effected by the usage of the DLR, it works the same as if you use the type object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top