Search code examples
c#inheritancemta

C# Inheritance Discussion from MTA


A question on a C# MTA exam I've done recently that has caused a large amount of discussion:

You have a class named Glass that inherits from a base class named Window. The Window class includes a protected method named break().

How should you call the Glass class implementation of the break() method?

A. Window.break();
B. Glass.break();
C. this.break();
D. base.break();

Can anyone give me a solid answer and rational for this?


Solution

  • I would do this by simply calling Break();, As long as the Break() method is not declared as virtual (which makes it possible to override it). Calling using this or base is simply redundant.

    However let´s say that Break() would be declared virtual then it would be the matter if you would want to call the implementation of Break() on the Window class (base.Break()) or on the Glass class (Break()/this.Break()).

    Consider the following code

    public class Window
    {
        public virtual void Break()
        {
            Console.WriteLine("Break in window called");
        }
    }
    
    public class Glass : Window
    {
        public override void Break()
        {
            Console.WriteLine("Break in Glass called");
        }
    
        public void DoSomething()
        {
            Break();
            this.Break(); // Same as above line
            base.Break();
        }
    }
    

    The output when calling DoSomething() on an instance of Glass would be

    Break in Glass called
    Break in Glass called
    Break in window called