• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 847
  • Last Modified:

virtual\override new keyword, differences

what is the difference between using the "new" keyword and the virtual\override
in both cases it prints the value 9 and after that 3 - execute the base method and after that the derived method

thanks in advance

keyword new
-----------
class A
    {
        public A()
        {
        }
        public void PrintVar()
        {
            Console.WriteLine("x = {0}",9);
        }
    }
   

    class B:A
    {
        public B()
        {
            PrintVar();
        }
        public new void PrintVar()
        {
            base.PrintVar();
            Console.WriteLine("x = {0}", 3);
        }
    }

static void Main(string[] args)
        {
            B b = new B();
            Console.ReadLine();
        }
       
       
       
virtual\overide
---------------
class A
    {
        public A()
        {
        }
        public virtual void PrintVar()
        {
            Console.WriteLine("x = {0}",9);
        }
    }
   

    class B:A
    {
        public B()
        {
            PrintVar();
        }
        public override void PrintVar()
        {
            base.PrintVar();
            Console.WriteLine("x = {0}", 3);
        }
    }
   
 static void Main(string[] args)
        {
            B b = new B();
            Console.ReadLine();
        }
0
eladr
Asked:
eladr
1 Solution
 
VovinECommented:
The main difference is that when you call a method on instance of object B on variable (reference) declared as instace A, then overrode method gets called, but new method does not, so the the base method is called.

if you had written some code before that uses class A method:

public static void doSomething(A par1)
{
   par1.PrintVar();
}

Then only most specialized virtual method gets called from descendants of A. New methods are not virtual and they will not get called if implemented in inheriting classes.

hope it helps :)
0
 
eladrAuthor Commented:
ok.thanks.
what actually u mean "...a method on instance of object B on variable (reference) declared as instace A..."
any little sample?...
10x again.
0
 
andrewjbCommented:
He means, rather than

B b = new B();

try it with

A b = new B();

and you'll see the difference
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now