Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you cast an object to a Tuple?

Tags:

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?

like image 228
Alexandru Avatar asked Jan 30 '13 13:01

Alexandru


2 Answers

Don't forget the () when you cast:

Tuple<string, string> selectedTuple = 
                  (Tuple<string, string>)comboBox1.SelectedItem;
like image 131
Cédric Bignon Avatar answered Sep 26 '22 00:09

Cédric Bignon


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.

like image 37
DomenPigeon Avatar answered Sep 26 '22 00:09

DomenPigeon