Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Downcasting in C#?

Downcasting in C#?

Scheduled Pinned Locked Moved C#
questioncsharphelp
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    Gerald Schwab
    wrote on last edited by
    #1

    How do I simulate downcasting in C#? public class foo { } public class bar : foo { } foo f = new foo(); // The following line // causes a run-time error. // InvalidCastException bar b = (bar)f; ************************ The following doesn't work either. This gives a compile error. public class foo { } public class bar : foo { public bar(){} public bar(foo f) { this = f; } public static explicit operator bar(foo f) { return new bar(f); } }

    P 1 Reply Last reply
    0
    • G Gerald Schwab

      How do I simulate downcasting in C#? public class foo { } public class bar : foo { } foo f = new foo(); // The following line // causes a run-time error. // InvalidCastException bar b = (bar)f; ************************ The following doesn't work either. This gives a compile error. public class foo { } public class bar : foo { public bar(){} public bar(foo f) { this = f; } public static explicit operator bar(foo f) { return new bar(f); } }

      P Offline
      P Offline
      Peter Stephens
      wrote on last edited by
      #2

      AFAIK that can't be done in C#. The 'foo' object never was a 'bar' object and can't be cast in that direction. A new 'bar' reference CAN be cast into a foo reference and then back into a 'bar' reference though. You cannot cast this way in a strongly typed language. You may be able to do this in C++ (with reinterpret_cast) but the virtual tables will be messed up and strange bugs WILL happen. -- Peter Stephens

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups