How do you cast an object to a Tuple?
Asked Answered
A

3

31

I create my Tuple and add it to a combo box:

comboBox1.Items.Add(new Tuple<string, string>(service, method));

Now I wish to cast the item as a Tuple, but this does not work:

Tuple<string, string> selectedTuple = 
                   Tuple<string, string>(comboBox1.SelectedItem);

How can I accomplish this?

Affiliation answered 30/1, 2013 at 13:44 Comment(0)
S
32

Don't forget the () when you cast:

Tuple<string, string> selectedTuple = 
                  (Tuple<string, string>)comboBox1.SelectedItem;
Siouxie answered 30/1, 2013 at 13:46 Comment(5)
Thanks! I got lost in all the brackets. I'll mark your post as the best answer once the timer expires!Affiliation
Or Tuple<string, string> selectedTuple = (comboBox1.SelectedItem as Tuple<string, string>);Nedra
@Nedra which will hide an error if for some unexpected reason it's not a tuple. If you know something is of type T then use a cast, if you know that something might be of type T but it's valid bahavior even if it's not use as and a null testRosalindarosalinde
@Rune FS Well depending on how he is using the tuple object, a check on null could make sense vs throwing an exception. Just giving him another option even though I know Cedric's answer is absolutely correct.Nedra
@Nedra yes that's exactly what I state that in the case he knows it should always be the specified tuple type cast is the appropriate option (because if the cast fails it is then by definition an exceptional situation) if the object could legally be something else asis the appropriate optionRosalindarosalinde
R
28

As of C# 7 you can cast very simply:

var persons = new List<object>{ ("FirstName", "LastName") };
var person = ((string firstName, string lastName)) persons[0];

// The variable person is of tuple type (string, string)

Note that both parenthesis are necessary. The first (from inside out) are there because of the tuple type and the second because of an explicit conversion.

Resinate answered 26/10, 2020 at 16:51 Comment(3)
I'd rather use: var person = ((string, string)) persons[0];Lachrymatory
Yes that's also possible but in this case you you would need to use person.Item1 and person.Item2 instead of person.firstName and person.lastNameResinate
C# 6 also supports this syntax.Sapajou
R
10

Your syntax is wrong. It should be:

Tuple<string, string> selectedTuple = (Tuple<string, string>)comboBox1.SelectedItem;

Alternatively:

var selectedTuple = (Tuple<string, string>)comboBox1.SelectedItem;
Rabble answered 30/1, 2013 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.