0

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.

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
codefluent
  • 125
  • 1
  • 11

2 Answers2

1

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.

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
0

In most uses of dynamic I come across, it does more harm than good. It's heavy and comes with no assured results.

dynamic is nothing more than object with a lot of compiler and runtime work on top of it.

If you don't know the shape of your tuples, you should know that all value tuple structs implement ITuple and there's an indexer for each element:

var value = (dictionary["key"] as ITuple)[0];
Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59