How to unbox tuple?
Asked Answered
T

1

5

I have boxed tuple:

(int, string) tuple = (1, "abc");
object box = tuple;

How to obtain tuple from box? What is the right syntax to cast object back to tuple?

My attempt:

var deconstruct = (int, string)box;

is obviously wrong:

Error CS1525 Invalid expression term 'int'

Error CS1525 Invalid expression term 'string'

Error CS1002 ; expected

Error CS0201 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

Tilbury answered 22/10, 2019 at 14:18 Comment(5)
have you tried (int, string) deconstruct = (int, string)box;Thapsus
mustoverride.com/tuples_conversionsCostanzo
The syntax of casts is (type) expr. The type of the tuple is (int, string). Ergo: ((int, string)) box.Winnow
@JeroenMostert, after seeing the answer its obvious, I was somehow blinded by already having one set of bracers.Tilbury
It's not the most readable syntax, even though it follows a logical pattern -- we can blame C for introducing that cast syntax in the first place (the tuple syntax seems fine).Winnow
T
12
ValueTuple<int, string> t = (ValueTuple<int, string>)box;

or

(int, string) t = ((int, string))box;
Typecast answered 22/10, 2019 at 14:23 Comment(1)
Easy! One pair for the tuple, the other for the cast.Fayefayette

© 2022 - 2024 — McMap. All rights reserved.