Final keyword in C#


Java has a final keyword, but C# does not have its implementation. For the same implementation, use the sealed keyword.

With sealed, you can prevent overriding of a method. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.

The following example won’t allow you to override the method display() because it has a sealed modifier for the ClassTwo derived class.

ClassOne is our base class, whereas ClassTwo and ClassThree are derived classes −

Example

class ClassOne {
   public virtual void display() {
         Console.WriteLine("Baseclass");
   }
}

class ClassTwo : ClassOne {
   public sealed override void display() {
      Console.WriteLine("ClassTwo:derivedClass");
   }
}

class ClassThree : ClassTwo {
   public override void display() {
      Console.WriteLine("ClassThree: Another Derived Class");
   }
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 21-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements