Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sealed must be used with override?

Tags:

c#

sealed

From msdn sealed (C# Reference)

"When applied to a method or property, the sealed modifier must always be used with override."

Why must it always be used with override?

like image 678
José D. Avatar asked Jan 23 '14 18:01

José D.


3 Answers

sealed prevents a method from being overriden by subclasses. If the method marked as sealed wasn't overridable in the first place, why would you mark it as sealed?

like image 93
dcastro Avatar answered Oct 19 '22 10:10

dcastro


Because there is not reason to add it to a property that does not override a property from another class. It you put the sealed modifier on a derived class's property, it is saying the anyone that derives from you cannot further override that property. If the property was never overridable to start with, there is no point in using sealed.

Basically, it is saying that subclasses must use the property the way you intended.

like image 20
clhereistian Avatar answered Oct 19 '22 10:10

clhereistian


Because structs are implicitly sealed, they cannot be inherited, "sealed" prevents a method from being overriden by subclasses.

See the example: In the following example, Z inherits from Y but Z cannot override the virtual function F that is declared in X and sealed in Y.

class X
{
    protected virtual void F() { Console.WriteLine("X.F"); }
    protected virtual void F2() { Console.WriteLine("X.F2"); }
}

Class Y inherits from class X, and define function F() as: sealed protected override void F().

class Y : X
{
    sealed protected override void F() { Console.WriteLine("Y.F"); }
    protected override void F2() { Console.WriteLine("Y.F2"); }
}

Class Z that inherits from Y where function F() was defined as sealed, you can´t override the function because its defined as "sealed"

class Z : Y
{
    // Attempting to override F causes compiler error CS0239. 
    // protected override void F() { Console.WriteLine("C.F"); }

    // Overriding F2 is allowed. 
    protected override void F2() { Console.WriteLine("Z.F2"); }
}

more info: sealed (C# Reference)

like image 21
Jorgesys Avatar answered Oct 19 '22 11:10

Jorgesys