+ 1
Derived Class(sub class) is not overriding method from its super class(base class) in C#
Am trying to override a method in the base class but its returning the code in the base class's method.... Here is my code using System; using System.Linq.Expressions; using Microsoft.VisualBasic; namespace ConsoleApp2 { class Person { public void ShowName() { Console.WriteLine("Am a human being"); } } class Dog : Person { static void ShowName() { Console.WriteLine("Am a dog"); } } static void Main(string[] args) { Dog d = new Dog(); d.ShowName(); } } When i run the code above it returns the code in the method contained in the super class...
3 ответов
+ 2
static methods are belong class scope. They will not accessed by object.. And those will not inherited into subclass..
So you are not overriding super class method..
static methods are accessed by class name.
Instance methods are accessed by object..
d.ShowName() call super class method..
Dog.ShowName() call Dog class static method..
+ 2
in addition to Jayakrishna🇮🇳
A method that is allowed to be overriden needs to be marked with the virtual keyword.
A method that want to override needs to be marked with override keyword.
Notice the error
warning CS0108: 'Dog.ShowName()' hides inherited member 'Person.ShowName()'.
https://code.sololearn.com/cywD89g91PK2
https://code.sololearn.com/c71c28xiyRqq
Please put your code in the playground, if you want to refer to it.
https://www.geeksforgeeks.org/c-sharp-method-overriding/
0
Thanks sneeze