Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# How to downcast an object

Tags:

c#

.net

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.

like image 222
Chin Avatar asked Jul 30 '09 07:07

Chin


2 Answers

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.

like image 90
Fredrik Mörk Avatar answered Sep 23 '22 12:09

Fredrik Mörk


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
}
like image 41
Sam Harwell Avatar answered Sep 22 '22 12:09

Sam Harwell