Casting Problem
-
I have an interesting and stupid problem, I have a class that is dirived from another class and I want to type cast the first class to the second class somewhere in the program as seen below. Class A { } Class B { } A FirstObject=new A(); B SecondObject; SecondObject=(B)A When I attempt to do this in WebApplication I get Specific Cast Not Valid. What am I doing wrong?? John
-
I have an interesting and stupid problem, I have a class that is dirived from another class and I want to type cast the first class to the second class somewhere in the program as seen below. Class A { } Class B { } A FirstObject=new A(); B SecondObject; SecondObject=(B)A When I attempt to do this in WebApplication I get Specific Cast Not Valid. What am I doing wrong?? John
Hi John, I don't think that you can cast classes, even if they derive from the same base class in C# (even tho this is legal in C++). Instead, something like this may get you where you want to go. Good luck! Nick. ----------------------------------------------------------- A Sample Run: D:\>ClassCasting.exe ClassA! ClassB! D:\> ----------------------------------------------------------- using System; namespace ClassCasting { /// /// Summary description for Class1. /// class ClassCasting { /// /// The main entry point for the application. /// [STAThread] static void Main(string[] args) { ClassA oClassA = new ClassA(); ClassB oClassB = new ClassB(); // Can't do this in C# yet! //oClassB = (ClassB) oClassA; // But.... you can do this! CoreClass oCoreClass = oClassA; oCoreClass.SomeMethod(); oCoreClass = oClassB; oCoreClass.SomeMethod(); } } abstract class CoreClass { // Define some common methods here. public abstract void SomeMethod(); } class ClassA : CoreClass { public override void SomeMethod() { Console.WriteLine("ClassA!"); } } class ClassB : CoreClass { public override void SomeMethod() { Console.WriteLine("ClassB!"); } } }