New Method Modifier

.New Method


New Method Modifier Program Output

.New Method Modifier

"A C# program which uses the "new" modifier to explicitly hide a method that is inherited from a base class."

This program defines a base class with two methods. A derived class hides one of the methods inherited from the base class by defining a "new" implementation for the method. The following C# features are used in the sample code:

  1. New Modifier - Explicitly hides a member that is inherited from a base class.
  2. New Operator - Creates objects from class and struct types. Also invokes constructors.
  3. Inheritance - Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes.

    New Method Modifier

    namespace newModifier
    {
        public class myBase
        {
            public void printLineX()
            {
                System.Console.WriteLine("X from myBase Class");
            }

            public void printLineY()
            {
                System.Console.WriteLine("Y from myBase Class");
            }
        }

        public class myDerived : myBase
        {
            // Hide printLineX from base class with "new" modifier
            new public void printLineX()
            {
                System.Console.WriteLine("X from myDerived Class");
            }
        }

        class Program
        {
            static void Header()
            {
                System.Console.WriteLine("**********************************************************");
                System.Console.WriteLine("*** Using 'new' Modifier to Hide Members of Base Class ***");
                System.Console.WriteLine("**********************************************************\n");
            }

            static void Main()
            {
                Program.Header();

                // Base Object
                myBase myClass2 = new myBase();
                System.Console.WriteLine("\n------------ Base Class ------------");
                myClass2.printLineX(); // Prints X Line from Base Class
                myClass2.printLineY(); // Prints Y Line from Base Class

                // Derived Object
                myDerived myClass = new myDerived();
                System.Console.WriteLine("\n------------ Derived Class ------------");
                myClass.printLineX(); // Prints X Line from Derived Class
                myClass.printLineY(); // Prints Y Line from Base Class

                System.Console.WriteLine();
            }
        }
    }