O'Reilly Forums: Interfaces (upcasting And Downcasting) - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Interfaces (upcasting And Downcasting) How to upcast and then downcast with a single line

#1 User is offline   darivuki 

  • New Member
  • Pip
  • Group: Members
  • Posts: 7
  • Joined: 18-March 14

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
0

#2 User is offline   AndrewStellman 

  • Andrew Stellman
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: O'Reilly Author
  • Posts: 803
  • Joined: 08-October 08
  • 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

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users