C#: Modifying method behavior in derived class using new keyword

This entry is part 52 of 71 in the series C#

In this example, we modify the method behavior in the derived class.

The ListBox constructor is based on the base class but it also adds a new parameter.

The DrawlControl method is also based on the base class but with an additional characteristic.

Derived Class
using System;

namespace Drawing
    public class Control
        // these members are private and thus invisible
        // to derived class methods
        private int top;
        private int left;

        public Control(int top, int left)
            this.top = top;
            this.left = left;

        public void DrawControl()
            Console.WriteLine("Drawing Control at {0}, {1}", top, left);

    public class ListBox : Control
        private string listboxContent; // new member variable

        // constructor adds a parameter
        public ListBox(int top, int left, string theContent)
            : base(top, left) // call base constructor with the keyword :base
            listboxContent = theContent;

        // a new version, note the keyword new
        public new void DrawControl()
            base.DrawControl(); // invoke the base method
            Console.WriteLine("Writing string to the ListBox: {0}",

    public class Program
        public static void Main()
            Control myControl = new Control(5, 10);

            ListBox lb = new ListBox(20, 30, "Hello world");


The new keyword in line 36 keeps the myControl and lb to access the right member DrawControl.  

The variables that have type Control(BaseClass) continue to access the members of Control(BaseClass), and the variable that has type ListBox(DerivedClass) continues to access members in DerivedClass first, and then to consider members inherited from BaseClass.


Series Navigation<< C#: Extending the staff base class
C#: Base Class’ Constructors >>

Leave a comment

Leave a Reply