-2

Possible Duplicate:
C#: new versus override

class BaseAppXmlLogReaders
    {
        public virtual void WriteLog() { }
        public void Add()
        { 
        }
    }
    class DerivedAppXmlLogReaders : BaseAppXmlLogReaders
    {
        public override void WriteLog()
        {

        }
        public new void Add()
        { }
    }

    class Demo
    {
        public static void Main()
        {
            BaseAppXmlLogReaders obj = new DerivedAppXmlLogReaders();
            obj.Add();//Call base class method
            obj.WriteLog();//call derived class method          
        }
    }

I am little bit confuse however it makes object of DerivedAppXmlLogReaders but it calls Add() method of base class and WriteLog() method of derived class.

Community
  • 1
  • 1
ND's
  • 2,155
  • 6
  • 38
  • 59

2 Answers2

0

It's because you handle it as BaseAppXmlLogReaders. If you use the following line, you'll call the Add method of the derived class.

var obj = new DerivedAppXmlLogReaders(); // or DerivedAppXmlLogReaders obj = ...

EDIT:

However, you can still call the method of the derived class in this way:

(obj as DerivedAppXmlLogReaders).Add();
laszlokiss88
  • 4,001
  • 3
  • 20
  • 26
  • classBase obj =new classDerived(); Means object of dervied class created i m right whatever class infront of new then creates object of that class – ND's Feb 01 '13 at 09:49
  • I know that, but the members of the dervived class will be hidden. – laszlokiss88 Feb 01 '13 at 09:51
  • why...I m not getting please elaborate – ND's Feb 01 '13 at 09:51
  • Because this is how it works. The Add method is not virtual, so it will be called on the type that holds the reference to the object(in your case it is the BaseAppXmlLogReaders). – laszlokiss88 Feb 01 '13 at 10:02
0

If you call a non-virtual method, the method of the type you are a holding the reference will be called, in your case BaseAppXmlLogReaders. If you are calling a virtual method, the framework will point the call to the "correct", overridden, method. That´s why virtual calls are slighty more costly and why it´s, in 99% of the cases, a bad idea to use new. I´ve yet to see a justified use of new.

Jobo
  • 1,084
  • 7
  • 14
  • classBase obj =new classDerived(); Means object of dervied class created i m right whatever class infront of new then creates object of that class – ND's Feb 01 '13 at 09:52
  • Yes, but, as i said, non-virtual methods will point to the classBase-method. That´s a fact and that´s how `new` works. `Virtual` tells the runtime to check if there´s an overridden method in the actual instance, `new` methods are ignored, because the base method isn´t `virtual`. The `sealed` keyword on a class would tell the runtime that it doesn´t have to check for overridden methods because there can´t be any. Don´t use `new` if you have control over the base class. – Jobo Feb 01 '13 at 09:56