1

In the following example, why does the math method with the new keyword still function even though the class that it's in derives from one where the overriden method is sealed? Isn't the whole point of having a method as sealed ensuring it cannot be inherited or virtual?

public class Program
{
    public static void Main(string[] args)
    {
        Utility u = new Utility();
        Entity e = new Entity();
        Last n = new Last();

        Console.WriteLine(u.math(2,3));
        Console.WriteLine(e.math(99,9));
        Console.WriteLine(n.math(4,4)); //Why doesn't this line give a compiler error?
    }
}

public class Utility
{
    public virtual int math(int x, int y)
    {
        return x + y;
    }
}

public class Entity : Utility
{
    public sealed override int math(int x, int y)
    {
        return x / y;
    }
}

public class Last : Entity
{
    public new int math(int x, int y)
    {
        return x * y + 100;
    }
}

Output:

5

11

116

ratboy
  • 63
  • 6

0 Answers0