2

Let me model my question like this.

I have a hierarchy where Dog, Cat, Bird are subclasses of the abstract class Animal. Bird has a new event BirdEvent that is not (and should not be) in Animal.

I have a class MyObject that has a field of type Animal (to take advantage of polymorphism). Let's assume that some instances of MyObject will fill their Animal field with Bird and others with Cat or Dog. If the Animal field contains an instance of Bird, I want to register for its BirdEvent. But as the field is of type Animal, it obviously cannot have a BirdEvent.

MyObject myObject= new Myobject();

if (myObject.Animal is Bird)
{
     myObject.Animal.BirdEvent += reactToBirdEvent;   
}

Is there a way I could reach BirdEvent? Or quite possibly, is my design flawed somewhere I didn't see?

purrduc
  • 135
  • 1
  • 5

2 Answers2

4

You can cast it to Bird:

MyObject myObject= new Myobject();

if (myObject.Animal is Bird)
{
      ((Bird)myObject.Animal).BirdEvent += reactToBirdEvent;   
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Pikoh
  • 7,582
  • 28
  • 53
  • Okay, this kind of casting was new to me. Thank you! – purrduc Feb 29 '16 at 12:57
  • 1
    @purrduc Note that this will actually cast the object twice, once for `is` and then again for the explicit cast. To avoid that it's better to use `as` and a `null` check. – juharr Feb 29 '16 at 12:59
  • Thx for your edit @TimSchmelter, it is more complete now – Pikoh Feb 29 '16 at 13:01
  • 2
    @juharr: [true](http://stackoverflow.com/a/496167/284240), but not for performance reasons. Actually, if `myObject` was a value type, the `as`+`null`-check is even [less efficient](http://stackoverflow.com/questions/1583050/performance-surprise-with-as-and-nullable-types) than the `is` + explicit cast. – Tim Schmelter Feb 29 '16 at 13:07
  • @juharr Noted, thanks. As long as there is any other indication that the object is of type `Bird`, the `is` can be left out. – purrduc Feb 29 '16 at 13:14
2

Simply cast your instance to Bird using the safe-cast-approach:

Bird myBird = myObject.Animal as Bird;
if (myBird != null)
{
      myBird.BirdEvent += reactToBirdEvent;   
}
Community
  • 1
  • 1
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111