Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sealed method in C#

Tags:

c#

sealed

I am a newbie in C#.I am reading about Sealed keyword.I have got about sealed class.I have read a line about Sealed method where we can make Sealed method also.The line was (By declaring method as sealed, we can avoid further overriding of this method.) I have created a demo but didn't understand that the meaning of above line and sealed method use. Below is my code:-

using System;  namespace ConsoleApplication2 {     class Program:MyClass     {         public override sealed void Test()         {             Console.WriteLine("My class Program");         }         static void Main(string[] args)         {             Program obj = new Program();             obj.Test();             Console.ReadLine();         }     }      class MyClass     {         public virtual void Test()         {             Console.WriteLine("My class Test");         }     }   } 

Please tell me why we use Sealed methods and what are the advantages of Sealed methods.

like image 961
Mohit Kumar Avatar asked Nov 11 '10 06:11

Mohit Kumar


People also ask

What is sealed method?

Sealed method is used to define the overriding level of a virtual method. Sealed keyword is always used with override keyword.

What is sealed in C?

A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended.

What is sealed class with example?

A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated. The design intent of a sealed class is to indicate that the class is specialized and there is no need to extend it to provide any additional functionality through inheritance to override its behavior.

Why we use sealed classes?

We use sealed classes to prevent inheritance. As we cannot inherit from a sealed class, the methods in the sealed class cannot be manipulated from other classes. It helps to prevent security issues.


1 Answers

Well, you are testing with only two levels of inheritance, and you are not getting to the point that you're "further overriding" a method. If you make it three, you can see what sealed does:

class Base {    public virtual void Test() { ... } } class Subclass1 : Base {    public sealed override void Test() { ... } } class Subclass2 : Subclass1 {    public override void Test() { ... } // Does not compile!    // If `Subclass1.Test` was not sealed, it would've compiled correctly. } 
like image 119
mmx Avatar answered Oct 08 '22 19:10

mmx