Sobes.tech
Junior — Middle

Is it possible to define a virtual function in a non-inheritable class?

sobes.tech AI

Answer from AI

In C#, a virtual function (method) is intended to be overridden in derived classes. If a class is declared as sealed (non-inheritable), then defining virtual methods in it is possible, but overriding them is not, since inheritance is prohibited.

Example:

sealed class MyClass
{
    public virtual void MyMethod()
    {
        Console.WriteLine("Virtual method in sealed class");
    }
}

Here, MyMethod is virtual, but since MyClass is sealed, no one can inherit it and override this method. Thus, virtual methods in a non-inheritable class are technically possible, but their purpose is limited.