0

The code below produces error and does not compile. But when we remove override keyword, it produces only warning, compiles and even does overriding.

Is there any logical explanation?

class Baseclass
{
    public void fun()
    {
        Console.WriteLine("Hi ");
    }

    public void fun(int i)
    {
        Console.Write("Hello ");
    }
}


class Derived : Baseclass
{
    public override void fun()
    {
        Console.Write("Bye ");
    }
}


class MyProgram
{
    static void Main(string[] args)
    {
        Derived d;
        d = new Derived();
        d.fun();
        d.fun(77);
        Console.Read();
    }
} 

2 Answers2

2

In C# you can only override method that is marked at virtual. Try this instead

class Baseclass
{
    public virtual void fun()
    {
        Console.WriteLine("Hi ");
    }
}


class Derived : Baseclass
{
    public override void fun()
    {
        Console.Write("Bye ");
    }
}

When you put override in function signatures, compile requires a matching virtual method (signatures and return type both) in base class that doesn't exists so an error is raised.

When you removes overrides keyword that actually hides method of BaseClass but doesn't overrides that. In this case compiler only raise warning and continues to compile.

There is a little difference between overriding and hiding See Overriding vs method hiding for more details

Community
  • 1
  • 1
Adnan Umer
  • 3,669
  • 2
  • 18
  • 38
  • OK. So it works like the `new` keyword would be used but is not so the warining appears :) now I understand the issue. Thanks! – Sebastian Xawery Wiśniowiecki Mar 21 '16 at 03:00
  • Well you need to put `new` keyword only if you want to hide the method. If you wanna override, mark the method in base class as virtual. Hiding the method will not show any polymorphic behavior. – Adnan Umer Mar 21 '16 at 03:02
0

C# contains a keyword virtual which allows you to mark members to be overridden in derived classes.

The reason as stated in the documentation is:

By default, methods are non-virtual. You cannot override a non-virtual method.

Why did the language designers do it this way where you have to explicitly state that a method can be overridden? I can't speak for them but it seems obvious they wanted to give programmers a safe way to avoid overriding members by mistake. That seems the most obvious win here.

So when designing a class you should mark classes you see as being usefully overridden as virtual.

You can read more on MSDN.

So you Baseclass will look like this:

class Baseclass
{
    public virtual void fun()
    {
        Console.WriteLine("Hi ");
    }

    public void fun(int i)
    {
        Console.Write("Hello ");
    }
}

Of course you could add virtual to the overloaded method taking an int as well.

Devon Burriss
  • 2,497
  • 1
  • 19
  • 21