Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# override modifier is mandatory in derive class for virtual/abstract methods of base class

public class Shapes
{
  public virtual void Color()
  {
    Console.WriteLine("Shapes");
  }
}

public class Square : Shapes
{
  public void Color()
  {
    Console.WriteLine("Square");
  }
}

public class Test
{ 
  public static void main()
  {
    Shapes s1 = new Shapes();
    s1.Color();
    Shapes s2 = new Square();
    s2.Color();
  }
}

I want to know if the base class has defined some methods virtual, then is it mandatory to override them in derive class? Similarly, If the base class method is abstract, we need to implement the method in derive class, but is override modifier is mandatory? What if override modifier is omitted.

like image 216
Sri Reddy Avatar asked Dec 03 '22 01:12

Sri Reddy


2 Answers

I want to know if the base class has defined some methods virtual, then is it mandatory to override them in derive class?

Definitely not. It is up to the derived class to decide whether or not to override the virtual method. Note that some classes will recommend that derived classes override a particular virtual method in some cases, but the compiler will not enforce that.

If the base class method is abstract, we need to implement the method in derive class, but is override modifier is mandatory?

Yes, you need to use the override keyword, otherwise the method will be hidden by the definition in the derived class.

If you actually run your code, you will see "Shapes" printed twice. That's because the Color() method in the Squares class isn't declared using the override keyword. As such, it hides the base class method. This means it will only be accessible through a variable of type Squares:

Squares s3 = new Squares();
s3.Color();

This will print "Square", since you're calling the method on a variable of the correct type.

like image 79
dlev Avatar answered Dec 24 '22 03:12

dlev


Take a look at this link, it may be useful.

A copy in that page:

To make a method virtual, the virtual modifier has to be used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class

like image 42
Tu Tran Avatar answered Dec 24 '22 03:12

Tu Tran