Created
December 11, 2017 13:52
-
-
Save nhoxbypass/19eaabbc5b2e8275d8403681abc1c75c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
namespace OverrideAndNew | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BaseClass bc = new BaseClass(); | |
DerivedClass dc = new DerivedClass(); | |
BaseClass bcdc = new DerivedClass(); | |
// The following two calls do what you would expect. They call | |
// the methods that are defined in BaseClass. | |
bc.Method1(); | |
bc.Method2(); | |
// Output: | |
// Base - Method1 | |
// Base - Method2 | |
// The following two calls do what you would expect. They call | |
// the methods that are defined in DerivedClass. | |
dc.Method1(); | |
dc.Method2(); | |
// Output: | |
// Derived - Method1 | |
// Derived - Method2 | |
// The following two calls produce different results, depending | |
// on whether override (Method1) or new (Method2) is used. | |
bcdc.Method1(); | |
bcdc.Method2(); | |
// Output: | |
// Derived - Method1 | |
// Base - Method2 | |
} | |
} | |
class BaseClass | |
{ | |
public virtual void Method1() | |
{ | |
Console.WriteLine("Base - Method1"); | |
} | |
public virtual void Method2() | |
{ | |
Console.WriteLine("Base - Method2"); | |
} | |
} | |
class DerivedClass : BaseClass | |
{ | |
public override void Method1() | |
{ | |
Console.WriteLine("Derived - Method1"); | |
} | |
public new void Method2() | |
{ | |
Console.WriteLine("Derived - Method2"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment