-3

Can someone explain me using the example below how type casting works. I came accross this code in a virtual academy session from microsoft: Windows Phone 8.1 Development for Absolute Beginners => Overview of common xaml controls

myTextBlock.Text = ((ComboBoxItem)Combo.SelectedItem).Content.ToString();

For those who see this as a duplicate, for me its about this specific code, not the explanation behind casting.

This Helps but i cant use it to explain code above

Nomistake
  • 893
  • 2
  • 17
  • 32

1 Answers1

1

SelectedItem is declared as Object

(ComboBoxItem)Combo.SelectedItem cast to the ComboBoxItem type

((ComboBoxItem)Combo.SelectedItem) makes you access SelectedItem as a ComboBoxItem

rducom
  • 7,072
  • 1
  • 25
  • 39
  • Why didnt they do something like this: myTextBlock.Text = Combo.SelectedItem.Content.ToString(); – Nomistake Jan 30 '15 at 15:48
  • Because Content don't exist on the "object" type, but exists on the "ComboBoxItem" type. Such a line would cause a compilation error. – rducom Jan 30 '15 at 15:49
  • Ok, (maybe) strange SelectedItem has no Content. Or Maybe that's because SelectedItem is to generic and is used in many cases (Also objects without Content)? – Nomistake Jan 30 '15 at 17:12