0

The purpose is to create a valueTuple dynamically from a collection. In this collection, values might be different Type. The created ValueTuple would have the same value type.

  IList<object> tupleElements = new List<object>();
  tupleElements.Add(16);
  tupleElements.Add("any string");
  var vt1 = ValueTuple.Create(tupleElements[0], tupleElements[1]);
  var vt2 = ValueTuple.Create(16, "any string");
  

From the debug information, the two valueTuples contain the same values. But, the type is different. vt1 is object,object. vt2 is int, string.

enter image description here

How to make vt1 is (int, string) type too?

I can't use the way to create vt2 because the elements type in collection is different each time. Next step, the element in list might be 1, "any string", 2, 3, "other string". At this moment, the ValueTuple would be (int, string, int, int, string) instead of (object,object,object, object, object).

Any suggestion is welcome! Thanks!

Community
  • 1
  • 1
Ethan
  • 11
  • 1
  • I strongly suspect you have an interesting idea what `var` means in C# and knowing an answer to the question as asked will not help you at all... but the question about creating generic types/instances at run-time is very common and you should be able to find more similar duplicates if one I selected is not to your taste. – Alexei Levenkov Apr 05 '20 at 04:01
  • Thanks! Using reflection to create an instance for the generic type and using var to get the value. Sounds great! I will have a try on it. An additional question: is any other way to do the similar thing except reflection?Since my code would run in Partial Trust mode, reflection might not be used in my code. – Ethan Apr 05 '20 at 04:43
  • You may look at expression trees too... Not something I can suggest useful guidance - I try to stay away from such generating code that generates code at run time ideas you are looking for. – Alexei Levenkov Apr 05 '20 at 05:11
  • I had a testing found var can't solve my problem. `dynamic` is the way help me out. And, the reflection is also unnecessary here. Code below will create two tuples with the same structure. `IList tupleElements = new List(); tupleElements.Add(16); tupleElements.Add("any string"); dynamic val1 = tupleElements[0]; dynamic val2 = tupleElements[1]; var vt1 = ValueTuple.Create(val1, val2); var vt2 = ValueTuple.Create(16, "any string");` – Ethan Apr 05 '20 at 15:02
  • Indeed you can let `dynamic` do reflection for you (it actually do more than just reflection - but that does not matter in this case)... It was not clear that you just needed tuple and was not planning to use them in the strongly typed code... Note that you don't need any complicated things you've shown - making single argument `dynamic` will switch whole code to run-time evaluation : `dynamic vt1 = ValueTuple.Create((dynamic)16, "test");`. – Alexei Levenkov Apr 06 '20 at 02:06

0 Answers0