Search code examples
c#dynamicvaluetuple

RuntimeBinderException when accessing ValueTuple item via dynamic


I am facing a really weird behavior of ValueTuple<T1,T2> passed from another assembly, accessed using dynamic. This code under specific circumstances throws RuntimeBinderException at the last line:

TupleTest(out var t);
(dynamic i1, dynamic i2) = t;
dynamic a = i1.Item1;

The message is:

'System.ValueType' does not contain a definition for 'Item1'

TupleTest function is defined in another assembly like this:

static void TupleTest(out ValueTuple<dynamic, dynamic> result) {
    result = default;

    result.Item1 = (new Priv(), new Priv());
    result.Item2 = (new Priv(), new Priv());
}

Where empty class Priv { } has no visibility modifiers.

However, if I add public class Priv, the issue goes away.

I understand, that binder could have had problems accessing instance members of Priv, but in this case I am not getting to that yet! All I am trying to do is to access field Item1 of ValueTuple.

Interestingly, if Priv implements some public interface IFoo, then replacing result.Item1 = (new Priv(), new Priv()); with result.Item1 = ((IFoo)new Priv(), (IFoo)new Priv()) allows dynamic a = i1.Item1 to succeed.

Does that mean, that I can't use dynamic at all to access any public fields, whose value type is private (can only be possible with generics), defined elsewhere?


Solution

  • This happens because Priv is not accessible to the code trying to access it.

    The accessibility of the types in dynamic must abide to the compiler rules.

    The error message is not very helpful, though.