What is the use case for C # allowing you to use the new virtual method?

Mostly a Java developer, I was a little surprised at the result when I once accidentally used a new keyword once instead of overriding it.

It seems that the new keyword removes the “virtuality” of the method at this level in the inheritance tree, so that calling the method on an instance of the child class that is omitted from the parent class will not allow the implementation method in the child class.

What are practical examples of using this behavior?

Explanation: I understand the use of the new when the parent is not virtual. I am more curious why the compiler allows you to combine new and virtual ones.

The following example illustrates the difference:

using System;

public class FooBar
{
    public virtual void AAA()
    {
        Console.WriteLine("FooBar:AAA");
    }

    public virtual void CCC()
    {
        Console.WriteLine("FooBar:CCC");
    }
}

public class Bar : FooBar
{
    public new void AAA()
    {
        Console.WriteLine("Bar:AAA");
    }

    public override void CCC()
    {
        Console.WriteLine("Bar:CCC");
    }
}

public class TestClass
{
    public static void Main()
    {
        FooBar a = new Bar();
        Bar b = new Bar();
        Console.WriteLine("Calling FooBar:AAA");
        a.AAA();
        Console.WriteLine("Calling FooBar:CCC");
        a.CCC();
        Console.WriteLine("Calling Bar:AAA");
        b.AAA();
        Console.WriteLine("Calling Bar:CCC");
        b.CCC();
        Console.ReadLine(); 
    }
}

This leads to the following conclusion:

Calling FooBar:AAA
FooBar:AAA
Calling FooBar:CCC
Bar:CCC
Calling Bar:AAA
Bar:AAA
Calling Bar:CCC
Bar:CCC
+5
3

:

  • Banana Fruit.
  • Peel Banana. Fruit Peel.
  • , Fruit.Peel
  • . Fruit.Peel? , - . Banana.Peel, , .

, , . Java Fruit.Peel, , , .

+15

, "" , , , . "" "" . , , , "new", . , .

- , .

: , "", , , . ", , "

+2

....

public class BaseCollection<T>
{
  // void return - doesn't seem to care about notifying the 
  // client where the item was added; it has an IndexOf method 
  // the caller can use if wants that information
  public virtual void Add(T item)
  {
    // adds the item somewhere, doesn't say where
  }

  public int IndexOf(T item)
  {
     // tells where the item is
  }
}

public class List<T> : BaseCollection<T>
{
  // here we have an Int32 return because our List is friendly 
  // and will tell the caller where the item was added
  new public virtual int Add(T item) // <-- clearly not an override
  {
     base.Add(item);
     return base.IndexOf(item);
  }
}

"" , List <T> "" BaseCollection <T> . (, , ). ... ", , Add void, - ".

0

All Articles