C # virtual inheritance or overriding

I have three classes.

Person → Employee → Manager

A person has a virtual method declared as

public virtual void saySomething()

Inside the employee i

public virtual void saySomething()

OR

public override void saySomething()

And I get the same behavior

Inside the manager I have

public override void saySomething()

Am I confused that I can use override instead of virtual? I thought you were using redefinition to denote the fact that this class redefined one of the functions of the base class.

How to stop a method from overriding? This is the last method.

+3
source share
3 answers

Adding public virtual void saySomething()to a subclass is a repeated declaration of the method (hiding the method, you will probably get a warning about this).

It will behave the same if you access it as:

Employee emp = ...
emp.saySomething();

but now add:

Person per = emp;
per.saySomething();

( override) . . , new:

new public virtual void saySomething() {...}

, - , sealed:

public sealed override void saySomething() {...}
+8

sealed, .

Employee, , Person. virtual Employee saySomething .

+2

You must use a sealed keyword .

+1
source

Source: https://habr.com/ru/post/1784670/


All Articles