The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.
The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations.
In C# structs are implicitly sealed; therefore, they cannot be inherited.
using System;
sealed class MyClass
{
public int x;
public int y;
}
class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
In the preceding example, if you attempt to inherit from the sealed class by using a statement like this:
class MyDerivedC: MyClass {} // Error
You will get the error message:'MyDerivedC' cannot inherit from sealed class 'MyBaseC'.
In C# a method can't be declared as sealed. However when we override a method in a derived class, we can declare the overrided method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method. using System;class MyClass1 { public int x; public int y;
public virtual void Method()
{
Console.WriteLine("virtual method");
}
}
class MyClass : MyClass1
{
public override sealed void Method()
{
Console.WriteLine("sealed method");
}
}
class MainClass
{
public static void Main()
{
MyClass1 mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
mC.Method();
}
}
Sealed Classes And Methods In C#
10:48 AM
Rajesh
Labels
.Net
(49)
.net course
(2)
.net event
(1)
.net traning
(6)
.net user group
(1)
.net3.0
(2)
.net3.0Features
(1)
.net4.0
(1)
Add Parameters to Command
(2)
ADO. NET
(14)
advance course
(3)
AJAX
(3)
ASP.Net Core
(26)
Autherntication
(1)
Code
(5)
Compailer
(1)
Data Reader
(2)
Data Set
(2)
Date
(1)
Date Format Retrival
(1)
Datef unctions
(1)
dot net classes
(6)
Dot Net Code
(5)
dot net user group
(1)
DotNet
(7)
dynamic data
(1)
dynamic text box
(1)
event
(1)
free .net training
(3)
Grid View
(4)
Interview Quetions
(5)
mugh
(1)
OOP S Concept
(1)
Partial Class
(1)
Sample Code
(25)
SQL
(5)
SQL Command
(2)
SQL Connection
(2)
SQL Date Format
(1)
SQL Date Queries
(1)
SQL Dates
(1)
State Management
(2)
Stored Procedures
(3)
traning
(26)
user event
(1)
user group
(1)
WCF
(2)
Web Config
(1)
Web Page Designs
(1)
Web Services
(1)
WF
(2)
Windows Work Flow
(1)
Working with WWF
(1)
WPF
(2)
WWF
(2)