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;
        }
    }
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.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.