Страницы

воскресенье, 14 февраля 2016 г.

Method override in C#

Hi, everyone! Recently, I decided to put all basic info about method overriding in one place. Keeping in mind that method, which is overriden may be virtual or not. Or you may just want to make name hiding (don't know why anybody may want to do that). So, here we go.

Non-virtual methods

class A
{
    void Foo() {}
}

class B: A
{
    void Foo() {} // compiler warning B.Foo() hides A.Foo()
}
To resolve warning:
class B: A
{
    new void Foo() {} // explicitly say to compiler, that hiding is intended using "new" keyword
}
To call method of base class:
new void Foo()
{
    base.Foo();
}

Virtual methods

class A
{
    virtual void Foo() {}
}

class B: A
{
    override void Foo() {}
}

Difference between virtual and non-virtual methods

code non-virtual virtual
A a = new B();
a.Foo(); A.Foo() B.Foo()
B b = (B)a;
b.Foo(); B.Foo() B.Foo()

With "new" keyword you may hide even virtual method of parent. But I don't see any reason to do that and code became more obfuscated

Any abstract method is virtual. But explicit typing "virtual" is forbidden (see section 10.6.6 from C# 3.0 specs)

Комментариев нет:

Отправить комментарий