30

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?

gideon
  • 19,329
  • 11
  • 72
  • 113
Alexandru
  • 12,264
  • 17
  • 113
  • 208

3 Answers3

32

Don't forget the () when you cast:

Tuple<string, string> selectedTuple = 
                  (Tuple<string, string>)comboBox1.SelectedItem;
gideon
  • 19,329
  • 11
  • 72
  • 113
Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
  • Thanks! I got lost in all the brackets. I'll mark your post as the best answer once the timer expires! – Alexandru Jan 30 '13 at 13:48
  • 1
    Or Tuple selectedTuple = (comboBox1.SelectedItem as Tuple); – TYY Jan 30 '13 at 13:48
  • 2
    @TYY 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 test – Rune FS Jan 30 '13 at 13:52
  • 1
    @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. – TYY Jan 30 '13 at 13:58
  • 1
    @TYY 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 `as`is _the_ appropriate option – Rune FS Jan 30 '13 at 14:10
26

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.

DomenPigeon
  • 618
  • 7
  • 12
  • I'd rather use: var person = ((string, string)) persons[0]; – Jess Rod Nov 24 '21 at 12:10
  • 2
    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.lastName` – DomenPigeon Nov 25 '21 at 16:26
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;
Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50