Final Form
Final Form

Reputation: 318

Is C# method sealed or virtual by default?

I know the definitions of virtual and sealed keywords, but if you don't use either of them with a method, can the method be overriden by default?

I am coming from vb.net background. It goes like this in vb.net (from MSDN):

If the Overridable or NotOverridable modifier is not specified, the default setting depends on whether the property or method overrides a base class property or method. If the property or method overrides a base class property or method, the default setting is Overridable; otherwise, it is NotOverridable.

I just want to know if that's also true in C#.

Upvotes: 7

Views: 3940

Answers (4)

NoviceProgrammer
NoviceProgrammer

Reputation: 3365

No, you cannot override a non-virtual method. The new keyword only hides the base class implementation and is not a good practice.

Discussion on this with Anders Hejlsberg here

Upvotes: 2

Wouter de Kort
Wouter de Kort

Reputation: 39898

No it cannot. You need to explicitly mark a method as virtual to allow it to be overridden in derived classes.

What you can do however, is hide a method by using the new keyword. (MSDN Documentation)

The sealed keyword is used on both class definitions and methods. It disallows inheriting from a class or overriding of a method. By default, if you don't use this keyword, others will be able to inherit from your class. (MSDN Documentation)

Upvotes: 6

Moha Dehghan
Moha Dehghan

Reputation: 18472

No. Unlike Java, in C# methods are not virtual by default. They neither are sealed, but you cannot override them, because they are normal methods.

Upvotes: 2

Servy
Servy

Reputation: 203837

By default methods in C# are not virtual.

Upvotes: 6

Related Questions