Jump to content


Photo

Interfaces (upcasting And Downcasting)


  • Please log in to reply
1 reply to this topic

#1 darivuki

darivuki

    New Member

  • Members
  • Pip
  • 7 posts

Posted 15 April 2014 - 09:27 AM

Hello,

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;
       someOtherScaryClown.Honk();
       Console.ReadKey();
}

"...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

AndrewStellman

    Andrew Stellman

  • O'Reilly Author
  • PipPipPipPipPipPipPipPipPipPipPip
  • 828 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);
    someOtherScaryclown.Honk();
    Console.ReadKey();
}

Andrew Stellman
Author, Head First C#
Building Better Software -- http://www.stellman-greene.com




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users