What is the purpose of sealed method in C#?

Using a sealed keyword along with a method means that the method cannot be overridden by the next level of derived classes. But there is a constraint while using sealed method: sealed method should be part of a derived class and the method must be an overridden method.



Here is an example demonstrating usage of sealed method:

namespace Application1 {
class baseClass {
public virtual void sampleMethod() {
Console.WriteLine("Executing sampleMethod of baseClass");
}
}
class derivedClass:baseClass {
public sealed override void sampleMethod() {
Console.WriteLine("Executing sampleMethod of derivedClass");
}
}
class derivedClass2 : derivedClass {
public override void sampleMethod() {
Console.WriteLine("Executing sampleMethod of derivedClass2");
}
}
}

In this example, you try to override the sealed method sampleMethod of derivedClass in derivedClass2. This is not permissible and you will end up in the following error:

'Application1.derivedClass2.sampleMethod()': cannot override inherited member 'Application1.derivedClass.sampleMethod()' because it is sealed

| What is Private Access Modifier in C#? | What is Protected Access Modifier in C#? | What is Protected Internal Access Modifier in C#? | What is Public Access Modifier in C#? | What is the difference between virtual and abstract keywords in .NET? | What is the importance of Microsoft Application Blocks in .NET Architecture? | What is the need for Factory Method in C# | What is the purpose of ArrayList in .NET? | What is the purpose of Datareader in ADO.NET? | What is the purpose of Dataset in ADO.NET? | What is the purpose of finally block in C#? | What is the purpose of interlocked class in .NET? | What is the purpose of main() function in C# | What is the purpose of ManualResetEvent in .NET? | What is the purpose of sealed method in C#? | What is the purpose of Thread.Join() method in .NET? | What is the purpose of Thread.Sleep() method in .NET? | What is the purpose of throw keyword in C#? | What is the usage of ENUM in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.