Interfaces (upcasting And Downcasting)

  • Please log in to reply
1 reply to this topic

#1 darivuki


    New Member

  • Members
  • Pip
  • 7 posts

Posted 15 April 2014 - 09:27 AM


i was wondering how could i upcast and downcast and object with a single line (the question is in the book, at the bottom of page 317, 3rd edition)

static void Main(string[] args) {
       ScaryScary fingersTheClown = new ScaryScary("big shoes", 14);
       FunnyFunny someFunnyClown = fingersTheClown;
       IScaryClown someOtherScaryClown = someFunnyClown as ScaryScary;

"...We put in some extra steps to show you that you could
upcast ScaryScary to FunnyFunny, and then downcast
that to IScaryClown. But all three of those lines could
be collapsed into a single line. Can you figure out how?..."

Thank you

#2 AndrewStellman


    Andrew Stellman

  • O'Reilly Author
  • PipPipPipPipPipPipPipPipPipPipPip
  • 832 posts
  • Gender:Male
  • Location:Brooklyn, NY
  • Interests:Author of: "Head First C#", "Beautiful Teams", "Head First PMP", "Applied Software Project Management"

Posted 15 April 2014 - 01:19 PM

Spoiler alert. You can replace the first three lines of Main() with this:

IScaryClown someOtherScaryclown = new ScaryScary("big shoes", 14);

so the whole method looks like this:

static void Main(string[] args)
    IScaryClown someOtherScaryclown = new ScaryScary("big shoes", 14);

Andrew Stellman
Author, Head First C#
Building Better Software --

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users