tags:

views:

282

answers:

7

Hi, 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.

I'm just beginning c# so any help appreciated.

+3  A: 
Section section = (Section)slide;

But you shouldn't do that - it's almost always a sign of flawed desgn.

maciejkow
+1  A: 

Simply cast it:

 Section section = (Section) slide;
Philippe Leybaert
+5  A: 

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.

Fredrik Mörk
+1  A: 
foreach(Slide slide in slidePack.slides)
{
     if(slide.type == SlideType.SECTION_MARKER)
     {
         Section sec = (Section)slide;

         //use sec.SectionProperty
     }
}
ArsenMkrt
+6  A: 

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
}
280Z28
A: 

You could do this as well if you only expect/want to process a single type

foreach(Section section in slidePack.slides.OfType<Section>())
{
    // Handle the current section object
}
CodeSpeaker
+1  A: 

(Putting this as a proper answer instead of a comment to the original post...)

This sounds like a downcast to me. Anyway, it's dangerous (or a design flaw) to do this. By downcasting to a more specialised type, you are expecting more from the object than it may be able to handle. If you feel the need to downcast, consider using interfaces.

Example:

class ClassWithX 
{
    public void X() {} 
}

class ClassWithXY 
{ 
    public void X() {} 

    public void Y() {}
}

class Test
{
    public static void Main(string[] args)
    {
        ClassWithX x = new ClassWithX();
        ((ClassWithXY) x).Y(); // Downcast, but x of type ClassWithX does not have Y()
    }
}

I hope this helps.

jeyoung