Quick actions

cmd+k|ctrl+k

Navigation

Languages

Inheritance new keyword

Snippet info

Language

Csharp

Visibility

public

Author

vibelyk

Created

2023-06-01T11:24:03.717878Z

Updated

2023-06-01T11:52:19.389428Z

using System;
using System.Collections.Generic;
using System.Linq;

class Employee
{
    public void DoWork()
    {
        Console.WriteLine("Employee class method");
    }
}

class Manager : Employee
{
    // keyword new needs only for explicit
    // stating that method shadowing, not overriding
    public new void DoWork()
    {
        Console.WriteLine("Manager class method");
    }
}

class MainClass {
    static void Main() {
        var manager = new Manager();
        manager.DoWork();
        
        BaseClass baseObj = new BaseClass();
        baseObj.Foo(); // Output: BaseClass Foo

        DerivedClass derivedObj = new DerivedClass();
        derivedObj.Foo(); // Output: DerivedClass Foo

        BaseClass derivedObjAsBase = new DerivedClass();
        derivedObjAsBase.Foo(); // Output: BaseClass Foo
    }
}

class BaseClass
{
    public void Foo()
    {
        Console.WriteLine("BaseClass Foo");
    }
}

class DerivedClass : BaseClass
{
    public new void Foo()
    {
        Console.WriteLine("DerivedClass Foo");
    }
}
INFO