Sunday, June 2, 2013

New Class Modifier

The new class modifier is used in derived classes when the derived class declared a member with the same name / signature which already exists in the base class.

When a member is declared in the derived class using the same name / signature of a member which already exists in the base class the following warning is thrown.

    class NewClass
    {
        public void MyFunction()
        {
        }
    }
    //
    class DerivedClass : NewClass
    {
        public void MyFunction()
        {
        }
    }

DerivedClass.MyFunction() hides inherited member NewClass.MyFunction(). Use the new keyword if hiding was intended.

As specified in the error message, adding the new keyword to the derived class member will help us avoid this error message as follows.


    class NewClass
    {
        public void MyFunction()
        {
            Console.WriteLine("Base class Function");
        }
    }
    //
    class DerivedClass : NewClass
    {
        public new void MyFunction()
        {
            Console.WriteLine("Derived class Function");
        }
    }

The hiding of the base member happens only within the scope of the derived class, if the base class member is called directly using an instance of the base class, it still calls the base class member.

    NewClass objNewClass = new NewClass();
    DerivedClass objDerivedClass = new DerivedClass();
    //
    objNewClass.MyFunction();
    objDerivedClass.MyFunction();

When the following lines of code gets executed the output will be as follows.

Base class Function

Derived class Function

Search Flipkart Products:
Flipkart.com

No comments: