What is sealed class in C#?

In today's post i am going to cover "What is Sealed class in C#  "?
Sealed is a keyword to declare a class as sealed.A class which can not be inherited is know as sealed class.

Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited. A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation.

Note:Sealed classes can never be used as base class.

Sealed class in C#

Below code will show how to declare sealed class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class CodiBucket
        {
            static void Main(string[] args)
            {
                SealedClass sealedCls = new SealedClass();
                int total = sealedCls.Add(4, 5);
                Console.WriteLine("Total = " + total.ToString());
            }
        }
 // Sealed class
sealed class SealedClass
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}
Sealed Method

When an is decorated with a sealed modifier, that method is said to be a sealed method.A sealed method overrides an inherited virtual method with the same signature. A sealed method shall also be marked with the override modifier. Use of the sealed modifier prevents a derived class from further overriding the method.

Here is the example to explain the above sentences.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class CodiBucket
        {
            public virtual void Method1()
            {
                Console.WriteLine("CodiBucket - Method 1");
            }
            public virtual void Method2()
            {
                Console.WriteLine("CodiBucket - Method 2");
            }
        }
        class Child1 : CodiBucket
        {
            public sealed override void Method1()
            {
                Console.WriteLine("CodiBucket Method 1");
            }
            public override void Method2()
            {
                Console.WriteLine("CodiBucket Method 2");
            }
        }
        class Child2 : Child1
        {
            public override void Method2()
            {
                Console.WriteLine("CodiBucket - Method 2");
            }
        }

Below i have tired to show how sealed keyword is used to prevent a method to be further overloaded.
Sealed class in C#


Hope you have enjoyed the post.Please provide your feedback.

Thanks.
What is sealed class in C#? What is sealed class in C#? Reviewed by CodiBucket on 06:10 Rating: 5

No comments:

Powered by Blogger.