I have the following list of slide objects. Based on the value of object's 'type' var I want to upcast the Slide object in the list. Is it possible?
foreach(Slide slide in slidePack.slides)
{
if(slide.type == SlideType.SECTION_MARKER)
{
//upcast Slide to Section
}
}
Section
extends Slide
and adds one more parameter.
Yes you can do that:
Section section = (Section)slide;
...or:
Section section = slide as Section;
The difference between those is that the first one will throw an exception if slide
cannot be cast to Section
, while the second one will return null
if the cast is not possible.
Here's the proper way to handle that cast.
Edit: There are ways to design programs to not need the test/cast you are looking for, but if you run into a case where to need to attempt to cast a C# object to some type and handle it different ways depending on success, this is definitely the way to do it.
Section section = slide as Section;
if (section != null)
{
// you know it's a section
}
else
{
// you know it's not
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With