How do you prevent a class from being inherited in c#

Category > CSHARP || Published on : Sunday, November 15, 2020 || Views: 625 || avoid inheritance of particular method


Here Pawan Kumar will explain how to avoid inheritance of particular method

In this post I will show you How do you prevent a class from being inherited in c#. The technique is very simple.

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication20
{
    class A
    {
        public virtual void Show()
        {
            Console.WriteLine("Show A");
        }
    }
    class B : A
    {
        public sealed override void Show()
        {
            Console.WriteLine("Show B");
        }
    }
    class C : B
    {
        public override void Show()  // Error  
               :sealed method in B cant be override
        {
            Console.WriteLine("Show B");
        }
    }
   class Demo
    {
        static void Main(string[] args)
        {
            B b = new B();

            A a = b;
            a.Show();
            Console.ReadLine();
        }
    }
}

Conclusion:-
So In this tutorial, We are going to How do you prevent a class from being inherited in c#. Happy Coding!!!!