new and virtual

We can mark virtual member with new keyword.

The different is shown in the following code.


using System;

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

public class Overrider : BaseClass
{
    public override void MyMethod() { Console.WriteLine("Overrider.MyMethod"); }
}

public class Hider : BaseClass
{
    public new void MyMethod() { Console.WriteLine("Hider.MyMethod"); }
}

class Program
{
    static void Main(string[] args)
    {
        Overrider over = new Overrider();
        BaseClass b1 = over;
        over.MyMethod();

        Hider h = new Hider();
        BaseClass b2 = h;
        h.MyMethod();

    }
}

The output:


Overrider.MyMethod
Hider.MyMethod
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.