How to access a virtual method of the based class from the derived class where the method have been redefined ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to access a virtual method of the based class from the derived class where the method have been redefined ?

31st Jul 2016, 2:29 PM
Ission
5 Answers
+ 1
A Virtual method is a method that is declared as virtual in a base class. Virtual method is that it can be redefined in one or more derived classes. each derived class can have its own version of a virtual method. You declare a method as virtual inside a base class by preceding its declaration with the keyword virtual. When a virtual method is redefined by a derived class, the override modifier is used. The process of redefining a virtual method inside a derived class is called method overriding. When overriding a method, the name, return type, and signature of the overriding method must be the same as the virtual method that is being overridden. Also, a virtual method cannot be specified as static or abstract. For Example: //Demonstrate a virtual method. using System; class Base{ //Create virtual method in the base class. public virtual void Who(){ Console.WriteLine("Who() in Base"); } } Class Derived1 : Base { //Override Who() in a derived class. public override void Who() { Console.WriteLine("Who() in Derived1"); } } Class Derived2 : Base { //Override Who() in another derived class. public override void Who() { Console.WriteLine("Who() in Derived2"); } } class OverrideDemo { static void Main() { Base baseOb = new Base(); Derived1 dOb1 = new Derived1(); Derived2 dOb2 = new Derived2(); } }
12th Dec 2016, 1:08 AM
Paras Jain
Paras Jain - avatar
0
i think you use the override keyword when redefining the method in the inherited class
2nd Aug 2016, 5:26 PM
Dakota Lewis
Dakota Lewis - avatar
0
didnt quite grasp your question but hope i helped anyway lol
2nd Aug 2016, 5:26 PM
Dakota Lewis
Dakota Lewis - avatar
0
No, i meant to access a base method from a derived class object :s In java we would use super() for exemple to access the base class constructor, or ClassName :: Method() so I am wondering how to do it in C#. I hope my question is a bit clearer now !
4th Aug 2016, 11:03 AM
Ission
0
Keyword *base* is your friend. The base keyword is used to refer to the base class when chaining constructors or when you want to access a member (method, property, anything) in the base class that has been overridden or hidden in the current class. ~ from stackoverflow.
14th Nov 2016, 8:42 PM
Oleg Pustylnik
Oleg Pustylnik - avatar