what are sealed methods?

  • sealed keyword can be used at the class level and a method level
  • using a sealed keyword on a method restricts the method from being overriden by any sub classes
  • It is used in cases when the method is already extended enough and any further extension is not desired.
class A
    {
        public virtual int Add()
        {
            Console.WriteLine("A.Add()");
            return 5 + 4;
        }
    }

    class B : A
    {
        public sealed override int Add()
        {
            Console.WriteLine("B.Add()");
            return 7 + 3;
        }
    }

    class C : B
    {
        // throws a compilation error here
        // 'C.Add()': cannot override inherited 
        // member 'B.Add()' because it is sealed
        public override int Add() 
        {
            Console.WriteLine("C.Add()");
            return 99 + 1;
        }
    }
  • sealed keyword can be used at the class level and a method level
  • using a sealed keyword on a method restricts the method from being overriden by any sub classes
  • It is used in cases when the method is already extended enough and any further extension is not desired.
class A
    {
        public virtual int Add()
        {
            Console.WriteLine("A.Add()");
            return 5 + 4;
        }
    }

    class B : A
    {
        public sealed override int Add()
        {
            Console.WriteLine("B.Add()");
            return 7 + 3;
        }
    }

    class C : B
    {
        // throws a compilation error here
        // 'C.Add()': cannot override inherited 
        // member 'B.Add()' because it is sealed
        public override int Add() 
        {
            Console.WriteLine("C.Add()");
            return 99 + 1;
        }
    }

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *