Click here to Skip to main content
15,173,031 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
Hi,
I have a doubt . When can a base class reference store derived class object and vice versa.
Like what will be the output of this and why?
C#
class A
    {
        public void x()
        {
            Console.WriteLine("hi");
        }
    }
    class B : A
    {
        public void y()
        {
            Console.WriteLine("hello");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A a = new B();
B b =new A();
b.x();
            a.y();
        }
    }
Posted
Updated 2-Dec-11 9:07am
v2
Comments
Wonde Tadesse 2-Dec-11 14:17pm
   
B b =new A();// Compile error, B is a sub type of A not vice versa

Your code will not compile.
C#
B b = new A();
Is not allowed, because B is derived from A and not the other way around. If the compiler allowed this,
then you could say:
C#
B b = new A();
b.y();
But what would happen at run time? The "y" method is not defined for objects of class A, so the method could not be called. The compiler prevents this run time error by refusing to let you make a design time assignment that would cause the problem.

It's a bit like saying a Ford is a Car, so every Car has a Ford badge - which is nonsense.
   
Comments
Wonde Tadesse 2-Dec-11 14:16pm
   
5+
Nikil S 2-Dec-11 16:28pm
   
+5
Why don't you run it under the debugger and see for yourself?
   
Comments
OriginalGriff 2-Dec-11 14:39pm
   
Because it won't compile...:laugh:
Nikil S 2-Dec-11 16:27pm
   
May be he wants to quiz us and also wants to know the reason behind the error.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900