2
Reply

What is the difference between new and override keywords in C#

17y
9.3k
0
Reply

    override is for polymorphic behavior of the member function/method. new is for member hiding / member shadowing.

    new keyword - New Definition for a method.

    overide keyword - Override existing definition for a method.

    using System;

    using System.Data;

    using System.Diagnostics;

    class Base

    {

    public virtual void Message()

    {

    Console.WriteLine("Base::Message");

    }

    ~Base()

    {

    Console.WriteLine("Base::Destructor");

    }

    }

    sealed class Derived : Base

    {

    public override/new void Message()

    {

    Console.WriteLine("Derived::Message");

    }

    ~Derived()

    {

    Console.WriteLine("Derived::Destructor");

    }

    }

    class Test

    {

    static void Main()

    {

    Base obj = new Derived() as Base;

    obj.Message();

    }

    }