0

I have below codes,

First code:

    {
        public virtual void Test()
        {
            Console.WriteLine("Parent Test");
        }

    }

    class Child : Parent
    {
        public override void Test()
        {
            Console.WriteLine("Child Test");
        }

        static void Main()
        {
            Child c = new Child();
            c.Test();

        }
    }

Output: Child Test

Second code:

    {
        public void Test()
        {
            Console.WriteLine("Parent Test");
        }

    }

    class Child : Parent
    {
        public void Test()
        {
            Console.WriteLine("Child Test");
        }

        static void Main()
        {
            Child c = new Child();
            c.Test();

        }
    }

Output: Child Test

I can able re-implement a function in child class without using virtual and override. Second code also gives same output then why I should virtual and override?

  • I would consider reading the docs [link](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual) [link](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override) – arlan schouwstra May 10 '19 at 13:55
  • 1
    I think that works but if you are using an IDE, you should get a warning or something. You can suppress the warning by using the `new` keyword. – bolkay May 10 '19 at 14:01

1 Answers1

0

In the second example you are not override the parent method. You create the method in the child class which has same signature as method in the parent class. If I'm not mistaken in this case Resharper suggest to use new keyword or change signatures in the both methods. The message of hidden parent implementation is appeared in this case.

See the 1st example in this C# Reference

SouXin
  • 1,565
  • 11
  • 17