Search code examples
c#dictionarydynamicvaluetuple

Casting value of Dictionary<SomeEnum, dynamic> to an tuple fails


I have a dictionary with a key of a known type (in the given example: string) and a tuple as value. I want to pass this dictionary around in the application and usually can unpack the data easily by using the key of the dictionary (in the real application it is not a string).

But I have one use case in which I'm only interested in the first element of the tuple, I only know how much other elements are in the tuple, but I don't know their type when I receive the dictionary.

// Some place of the application defines the dictionary like this and adds some values...
var dictionary = new Dictionary<string, dynamic>();
dictionary.Add("key", ("I'm interested in this tuple element only", new List<int>().ToImmutableList()));


// In some other place of the application, I get the dictionary from above, but I'm interested only 
// in the first element of the tuple, from the other elements I don't know the type so I try
// to access it like:
(string valueOfInterest, object) element = dictionary["key"];    

// Do something with valueOfInterest

But this code gives me an

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 
Cannot implicitly convert type System.ValueTuple<string,System.Collections.Immutable.ImmutableList<int>>' 
to 'System.ValueTuple<string,object>'

So I'm wondering how it is possible (or if it is possible at all), to access only the first element of the tuple and "discard" the others by converting them to object.


Solution

  • If you'll need the first value only, try to use unnamed tuple syntax and get the Item1 property.

    var element = dictionary["key"];
    var value = element.Item1;
    

    It'll work until the value in a dictionary is a Tuple.

    According to Resolution of the Deconstruct method specs

    This implies that rhs cannot be dynamic and that none of the parameters of the Deconstruct method can be type arguments.