Give an example of using a Sealed class in C#.
What is sealed class in C#?
1487
09-Sep-2019
Anonymous User
09-Sep-2019Below is the sample code of sealed class in C# :-
Example (1). class X {}
sealed class Y : X {}
//Sealed methods –
class A
{
protected virtual void First() { }
protected virtual void Second() { }
}
class B : A
{
sealed protected override void First() {}
protected override void Second() { }
}
Note :- If any class inherits from class “B” then method – “First” will not be overridable as this method is sealed in class B.
Example (2). // C# code to define
// a Sealed Class
using System;
// Sealed class
sealed class SealedClass {
// Calling Function
public int Add(int a, int b)
{
return a + b;
}
}
class Program {
// Main Method
static void Main(string[] args)
{
// Creating an object of Sealed Class
SealedClass slc = new SealedClass();
// Performing Addition operation
int total = slc.Add(6, 4);
Console.WriteLine("Total = " + total.ToString());
}
}