New Keyword in C#

 

# new keyword 

1.Instance Creation:- The new operator creates a new instance of a type.To create a new instance of a type, you typically invoke one of the constructors of that type using the new operator.


2.Method Hiding:-You can also use the new keyword as a member declaration modifier. When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version.


Example:-

    class BaseClass

    {

        public void Print()

        {

            Console.WriteLine("I am in BaseClass");

        }

    }

 

    class DerivedClass : BaseClass

    {

        public new void Print()      //Method Hidding

        {

            Console.WriteLine("I am in DerivedClass");

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            DerivedClass obj = new DerivedClass();     //Instance Creation

            obj.Print();

        }

    }


No comments:

Post a Comment