Downcasting in C#?
-
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); } }
-
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); } }
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