Click here to Skip to main content
16,016,263 members
Please Sign up or sign in to vote.
4.20/5 (2 votes)
See more:
Hi Friends.,

I am confused with the below program:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Learn
{
    class Program
    {
        static void Main(string[] args)
        {
            // Reference B through A.
            A ab = new B();
            ab.Y();

            // Reference C through A.
            A ac = new C();
            ac.Y();

            Console.Read();
        }
    }

    class A
    {
        public virtual void Y()
        {
            // Used when C is referenced through A.
            Console.WriteLine("A.Y");
        }
    }

    class B : A
    {
        public override void Y()
        {
            // Used when B is referenced through A.
            Console.WriteLine("B.Y");
        }
    }

    class C : A
    {
        new public void Y()
        //public void Y() // Can be "new public void Y()"
        {
            // Not used when C is referenced through A.
            Console.WriteLine("C.Y");
        }
    }
}


B.Y
A.Y

I got this example from dotnetperls

As per their tips I understood that we can Hide the function of base class in derived class using New Modifier keyword.

In the above sample program I have a class C which inherits class A. Here I am using new keyword to hide the base class function. But still it is displaying the output as A.Y instead of C.Y.

It would be great if any one can explain me about this.
Posted

1 solution

Its because you are writing.

C#
A ac = new C();

instead of
C#
C ac = new C();


variable ac is remembered as baseclass A since you reference it as such.

You can also try to cast ac into C, by doing this after your ac.Y();

C#
((C)ac).Y();
 
Share this answer
 
v2
Comments
willington.d 6-May-14 1:24am    
Then what is the use of NEW keyword here???
Per Söderlund 6-May-14 3:03am    
In your example its of little use.

In class A, if method Y wasnt marked as virtual you wouldnt be able to override it in B.
But you would still be able to hide it with C and make a "new" method.

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