New vs Override

New vs Override 

Override

  • Override method actually override the virtual method.
  • When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used.
  • This indicates for the compiler to use the last defined implementation of a method i.e. override the last implented method.
  • if you want to prevent anymore overridden from inherited class then use sealed keyword along with override.

New

  • It actually hides the base class method.
  • The new modifier instructs the compiler to use your implementation instead of the base class implementation. Any code that is not referencing your class but the base class will use the base class implementation.
  • new keyword doesn’t allow the method to be more overridden.

Example:

class BaseClass
{
public virtual void WhichClass()
{
System.Console.WriteLine(“BASE CLASS”);
}
}

class NewClass : BaseClass
{
public new void WhichClass()
{
//base.WhichClass();
System.Console.WriteLine(“NEW CLASS”);
}
}

class OverrideClass : BaseClass
{
public override void WhichClass()
{
//base.WhichClass();
System.Console.WriteLine(“OVERRIDE CLASS”);
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bObj = new BaseClass();
bObj.WhichClass();
System.Console.WriteLine(“———-“);

NewClass nObj = new NewClass();
nObj.WhichClass();
System.Console.WriteLine(“———-“);

BaseClass bnObj = new NewClass();
bnObj.WhichClass();
System.Console.WriteLine(“———-“);

OverrideClass oObj = new OverrideClass();
oObj.WhichClass();
System.Console.WriteLine(“———-“);

BaseClass boObj = new OverrideClass();
boObj.WhichClass();
System.Console.WriteLine(“———-“);

Console.ReadLine();
}
}

1 Comment

Filed under .Net, C#

One response to “New vs Override

  1. These are in fact wonderful ideas in about blogging. You have touched
    some good factors here. Any way keep up wrinting.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s