Click here to Skip to main content
15,909,747 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
namespace ConsoleApplication1
{
    class A
    {
        public void Amethod()
        {
            Console.WriteLine("Amethod");
        }
    }

    class B : A
    {
        public new void Bmethod()
        {
            Console.WriteLine("Bmethod");
        }
    }




    class Program
    {
        static void Main()
        {

            A ref2 = new B();

            ref2.Amethod(); // how here only A class method is accessible ? Please explain

            B ref3 = new B();

            ref3.Amethod();
            ref3.Bmethod();

        }
    }
}
In the above code, how here only A class method is accessible? Please explain.
Posted
Updated 1-Jul-13 21:08pm
v2

1 solution

Because your variable ref2 is declared as a type A, the compiler will only access A class properties and methods - because despite you assigning a B instance to it in this case, ref2 is not a B. It contains an instance of B, because you don't change it, but that may not last.

You are perfectly at liberty to change it later to a A class instance.

It's a bit like going shopping: is A is Vegetable and B is Carrot - because a Carrot is a type of Vegetable you can put "Vegetable" on your shopping list and come back with a Carrot. But you could also come back with a Potato, because that is also a Vegetable. But Potato does not have the "Orange colour" property that Carrot does, so you can't say "Vegetable has Orange colour".
 
Share this answer
 
Comments
lukeer 2-Jul-13 3:10am    
Wow. What an analogy. Time for breakfast.

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