RoR
RoR

Reputation: 16462

C# inheritance virtual or override

I have three classes.

Person -> Employee -> Manager

Person has a virtual method declared as

public virtual void saySomething()

Inside of Employee I have

public virtual void saySomething()

OR

public override void saySomething()

And I get the same behavior

Inside of Manager I have

public override void saySomething()

I'm confused with the fact that I can use override in replace of virtual? I thought you use override to signify the fact that this class has overridden one of the base class function.

How do I stop a method from being overriden? This is the last method.

Upvotes: 3

Views: 2524

Answers (3)

Matthew Abbott
Matthew Abbott

Reputation: 61589

You can use the sealed keyword to stop a virtual being overridden any further in your inheritance hierarchy.

Your use of override is correct in Employee, you want to override the default implementation provided by Person. virtual in the Employee type for the saySomething method is incorrect.

Upvotes: 2

You have to use sealed key word.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062512

Adding public virtual void saySomething() in the subclass is re-declaring the method (method-hiding; you probably get a warning about that).

It will behave the same if you access it as:

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

but now add:

Person per = emp;
per.saySomething();

With polymorphism (via override) they should do the same thing. But via method-hiding they won't. To explicitly hide a method, use new:

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

or to stop something being overridden any further, use sealed:

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

Upvotes: 8

Related Questions