How can you allow class to be inherited and prevent the method from being overridden in c#?
-
Don't use the `virtual` keyword? – 41686d6564 stands w. Palestine Jan 13 '21 at 14:32
-
2Probably *sealed methods* will help you. https://stackoverflow.com/questions/4152049/sealed-method-in-c-sharp – kogonidze Jan 13 '21 at 14:33
2 Answers
As it mentioned in the answer above, you can have sealed method only when it is overriden.
You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
By default, in C# every method is sealed, because overriding is not possible if this method is not declared in the parent class as virtual.
For example if you have two classes Person and Employee:
public class Person
{
public string GetName()
{
return "Person";
}
}
public class Employee : Person
{
public string GetName()
{
return "Employee";
}
}
in this example, it seems that Employee
class has the same GetName()
method as Person
has but it is not override, it is a quite new method and you still can call base method inside the child class.
P.S in this case it is recommended to use new
there like that: public new string GetName()
If you want to make the method sealed, such that you get compilation error when you try to rewrite, override (write the method with the same name, return type and parameters) parent method, there is no way to do that in C#.

- 3,422
- 6
- 25
- 42
What do you mean "Prevent from been overriden?" You can try this:
public class TestClass
{
public sealed override string ToString() => "";
}
but it works with overriden methods. Actually it says that virtual method won't be overriden anymore in the "inheritance line".
P.S. But looks like that you want to solve problem with a wrong way, please, explain better.

- 3,422
- 6
- 25
- 42

- 827
- 1
- 5
- 17