Method hiding plus overriding calling decision - c#

In case of method overriding based on the type referent object hold method call will be decided.
In case of method hiding based on type of object method call will be decided.
Can any one explain me the method calling decision in overriding + hiding.
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public override void DoIt()
{
}
}
public class Derived1 : Derived
{
public new void DoIt()
{
}
}
class Program
{
static void Main(string[] args)
{
Base b = new Derived();
Derived d = new Derived();
#1 b.DoIt(); // Calls Derived.DoIt
#2 d.DoIt(); // Calls Derived.DoIt
b = new Derived1();
d = new Derived1();
#3 b.DoIt(); // Calls Derived.DoIt
#4 d.DoIt();
}
}
#1 and #2 call Derived.DoIt because of run-time polymorphism.
#4 called Derived.DoIt because d is of type Dreived (Method hiding).
But why #3 called Derived.DoIt.
What is the calling sequence in case of overiding plus hiding in c#.
Thanks in advance

Because #3 is an instance of Base type. Here, the last derived method of Base resides in Derived class and hence it is being called.
new / method hiding / shadowing is different than method overriding in the sense that override means that you are customizing the base method whereas new means you are just providing a different implementation for the same method name.

In Method overriding it is decided on run-time which type's method to be called, but method hiding or shadowing is compile time thing, the compiler knows at compile time that which type's method is to called, when you use new keyword in derived type in method signature instead of override, that means that if you will call using reference of base class it will call base class implementation and if you use derived class reference it will call derived class method implementation.
The derived class implementation get's hidden from base class.
If you write it like this:
b = new Derived1();
b.DoIt() // (run-time) will call Dervied method implementation as Dervied has overridden
// so calling via base reference will call overridden implementation if any
//otherwise base class implementation will get called
Derived1 d1 = (Derived1)b;
d1.DoIt(); // (compile time) will call Derived1 method implementation due to hiding in Derived1
Derived d = (Derived)b;
d.DoIt(); // (run-time) will call Derived method implementation due to override

#3 calls Derived.DoIt() because the method was only hidden, it is still externally callable if using the appropriate cast. The variable b of is of type Base, and so you are accessing the methods available to Base. This is the one that is overwritten via Derived, so your result is the one from Derived.DoIt. Would you have a variable of type Derived1 and did a call to DoIt there, Derived1.DoIt would have been called instead.
public class Base
{
public virtual void DoIt()
{
Console.WriteLine("Base.DoIt was called!");
}
}
public class Derived : Base
{
public override void DoIt()
{
Console.WriteLine("Derived.DoIt was called!");
}
}
public class Derived1 : Derived
{
public new void DoIt()
{
Console.WriteLine("Derived1.DoIt was called!");
}
}
class Program
{
static void Main(string[] args)
{
Base b = new Derived();
Derived d = new Derived();
Console.WriteLine("#1");
b.DoIt();
Console.WriteLine("#2");
d.DoIt();
b = new Derived1();
d = new Derived1();
Console.WriteLine("#3");
b.DoIt();
Console.WriteLine("#4");
d.DoIt();
Console.WriteLine("#5");
Derived1 e = new Derived1();
e.DoIt();
Console.ReadKey();
}
}

Related

Why are the last 2 lines outputting what they are?

Can someone help me understand
Is this statement correct: BaseClass bcdc = new DerivedClass(); which means bcdc is of type BaseClass class, and its value is of type DerivedClass object? Also, what does that mean and why would an object be instantiated like that as opposed to having the class type be the same as the new object being instantiated, as in DerivedClass dc = new DerivedClass()?
Why bcdc.Method1() => Derived-Method1. Is it because the keyword override is used, and is so overriding the virtual Method1?
Why bcdc.Method2() => Base-Method2. I am confused because the new key word in the DerivedClass should be hiding Base-Method2? I thought that was the functionality of the new keyword.
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public void Method2()
{
Console.WriteLine("Base - Method2");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass(); //bc is of type BaseClass, and its value is of type BaseClass
DerivedClass dc = new DerivedClass(); //dc is of type DerivedClass, and its value is of type DerivedClass
BaseClass bcdc = new DerivedClass(); //bcdc is of type BaseClass, and its value is of type DerivedClass.
bc.Method1(); //Base - Method1
bc.Method2(); //Base - Method2
dc.Method1(); //Derived - Method1
dc.Method2(); //Derived - Method2
bcdc.Method1(); //Derived - Method1. ??
bcdc.Method2(); //Base - Method2. ??
}
} ```
which means bcdc is of type BaseClass class, and its value is of type DerivedClass object?
Yes. I would however prefer to call it a DerivedClass object with a BaseClass reference
Also, what does that mean and why would an object be instantiated like that as opposed to having the class type be the same as the new object being instantiated, as in DerivedClass dc = new DerivedClass()?
One case is when you want to call an explicit interface method. However, a very similar and more common case would happen if you call a method: MyMethod(BaseClass bcdc).
In this simple program all types are easily known at compile time. But for larger programs this would not be the case, a method take a BaseClass parameter that can have a bunch of different implementations, and all the implementations might not be known when the code is compiled.
Why bcdc.Method1() => Derived-Method1. Is it because the keyword override is used, and is so overriding the virtual Method1?
Yes, for methods marked as virtual the compiler will insert a check that forwards the method call to the overridden method based on the actual object type, i.e. DerivedClass. This is sometimes called virtual dispatch or dynamic dispatch. I.e. the method will be selected dynamically at runtime based on the object type.
Why bcdc.Method2() => Base-Method2. I am confused because the new key word in the DerivedClass should be hiding Base-Method2? I thought that was the functionality of the new keyword.
Method2 is not virtual, so there will be no dynamic dispatch. So the reference type, i.e. BaseClass, will be used to determine the called method. This is called static dispatch, i.e. the called method can be determined statically at compile time.

Polymorphism misunderstanding; accidentally typed 'virtual' instead of 'override' with unexpected result [duplicate]

What are differences between declaring a method in a base type "virtual" and then overriding it in a child type using the "override" keyword as opposed to simply using the "new" keyword when declaring the matching method in the child type?
I always find things like this more easily understood with pictures:
Again, taking joseph daigle's code,
public class Foo
{
public /*virtual*/ bool DoSomething() { return false; }
}
public class Bar : Foo
{
public /*override or new*/ bool DoSomething() { return true; }
}
If you then call the code like this:
Foo a = new Bar();
a.DoSomething();
NOTE: The important thing is that our object is actually a Bar, but we are storing it in a variable of type Foo (this is similar to casting it)
Then the result will be as follows, depending on whether you used virtual/override or new when declaring your classes.
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
public class Test
{
public static void Main ()
{
Foo test = new Bar ();
Console.WriteLine (test.DoSomething ());
}
}
This prints false, if you used override it would have printed true.
(Base code taken from Joseph Daigle)
So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.
Here's some code to understand the difference in the behavior of virtual and non-virtual methods:
class A
{
public void foo()
{
Console.WriteLine("A::foo()");
}
public virtual void bar()
{
Console.WriteLine("A::bar()");
}
}
class B : A
{
public new void foo()
{
Console.WriteLine("B::foo()");
}
public override void bar()
{
Console.WriteLine("B::bar()");
}
}
class Program
{
static int Main(string[] args)
{
B b = new B();
A a = b;
a.foo(); // Prints A::foo
b.foo(); // Prints B::foo
a.bar(); // Prints B::bar
b.bar(); // Prints B::bar
return 0;
}
}
The new keyword actually creates a completely new member that only exists on that specific type.
For instance
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
The method exists on both types. When you use reflection and get the members of type Bar, you will actually find 2 methods called DoSomething() that look exactly the same. By using new you effectively hide the implementation in the base class, so that when classes derive from Bar (in my example) the method call to base.DoSomething() goes to Bar and not Foo.
Beyond just the technical details, I think using virtual/override communicates a lot of semantic information on the design. When you declare a method virtual, you indicate that you expect that implementing classes may want to provide their own, non-default implementations. Omitting this in a base class, likewise, declares the expectation that the default method ought to suffice for all implementing classes. Similarly, one can use abstract declarations to force implementing classes to provide their own implementation. Again, I think this communicates a lot about how the programmer expects the code to be used. If I were writing both the base and implementing classes and found myself using new I'd seriously rethink the decision not to make the method virtual in the parent and declare my intent specifically.
virtual / override tells the compiler that the two methods are related and that in some circumstances when you would think you are calling the first (virtual) method it's actually correct to call the second (overridden) method instead. This is the foundation of polymorphism.
(new SubClass() as BaseClass).VirtualFoo()
Will call the SubClass's overriden VirtualFoo() method.
new tells the compiler that you are adding a method to a derived class with the same name as a method in the base class, but they have no relationship to each other.
(new SubClass() as BaseClass).NewBar()
Will call the BaseClass's NewBar() method, whereas:
(new SubClass()).NewBar()
Will call the SubClass's NewBar() method.
The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding.
Check out the folllowing links for more information...
MSDN and Other
new keyword is for Hiding. - means you are hiding your method at runtime. Output will be based base class method.
override for overriding. - means you are invoking your derived class method with the reference of base class. Output will be based on derived class method.
My version of explanation comes from using properties to help understand the differences.
override is simple enough, right ? The underlying type overrides the parent's.
new is perhaps the misleading (for me it was). With properties it's easier to understand:
public class Foo
{
public bool GetSomething => false;
}
public class Bar : Foo
{
public new bool GetSomething => true;
}
public static void Main(string[] args)
{
Foo foo = new Bar();
Console.WriteLine(foo.GetSomething);
Bar bar = new Bar();
Console.WriteLine(bar.GetSomething);
}
Using a debugger you can notice that Foo foo has 2 GetSomething properties, as it actually has 2 versions of the property, Foo's and Bar's, and to know which one to use, c# "picks" the property for the current type.
If you wanted to use the Bar's version, you would have used override or use Foo foo instead.
Bar bar has only 1, as it wants completely new behavior for GetSomething.
Not marking a method with anything means: Bind this method using the object's compile type, not runtime type (static binding).
Marking a method with virtual means: Bind this method using the object's runtime type, not compile time type (dynamic binding).
Marking a base class virtual method with override in derived class means: This is the method to be bound using the object's runtime type (dynamic binding).
Marking a base class virtual method with new in derived class means: This is a new method, that has no relation to the one with the same name in the base class and it should be bound using object's compile time type (static binding).
Not marking a base class virtual method in the derived class means: This method is marked as new (static binding).
Marking a method abstract means: This method is virtual, but I will not declare a body for it and its class is also abstract (dynamic binding).
using System;
using System.Text;
namespace OverrideAndNew
{
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
// The following two calls do what you would expect. They call
// the methods that are defined in BaseClass.
bc.Method1();
bc.Method2();
// Output:
// Base - Method1
// Base - Method2
// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
dc.Method1();
dc.Method2();
// Output:
// Derived - Method1
// Derived - Method2
// The following two calls produce different results, depending
// on whether override (Method1) or new (Method2) is used.
bcdc.Method1();
bcdc.Method2();
// Output:
// Derived - Method1
// Base - Method2
}
}
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public virtual void Method2()
{
Console.WriteLine("Base - Method2");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
}

Why in this code the output of the virtual functions is like this? [duplicate]

What are differences between declaring a method in a base type "virtual" and then overriding it in a child type using the "override" keyword as opposed to simply using the "new" keyword when declaring the matching method in the child type?
I always find things like this more easily understood with pictures:
Again, taking joseph daigle's code,
public class Foo
{
public /*virtual*/ bool DoSomething() { return false; }
}
public class Bar : Foo
{
public /*override or new*/ bool DoSomething() { return true; }
}
If you then call the code like this:
Foo a = new Bar();
a.DoSomething();
NOTE: The important thing is that our object is actually a Bar, but we are storing it in a variable of type Foo (this is similar to casting it)
Then the result will be as follows, depending on whether you used virtual/override or new when declaring your classes.
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
public class Test
{
public static void Main ()
{
Foo test = new Bar ();
Console.WriteLine (test.DoSomething ());
}
}
This prints false, if you used override it would have printed true.
(Base code taken from Joseph Daigle)
So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.
Here's some code to understand the difference in the behavior of virtual and non-virtual methods:
class A
{
public void foo()
{
Console.WriteLine("A::foo()");
}
public virtual void bar()
{
Console.WriteLine("A::bar()");
}
}
class B : A
{
public new void foo()
{
Console.WriteLine("B::foo()");
}
public override void bar()
{
Console.WriteLine("B::bar()");
}
}
class Program
{
static int Main(string[] args)
{
B b = new B();
A a = b;
a.foo(); // Prints A::foo
b.foo(); // Prints B::foo
a.bar(); // Prints B::bar
b.bar(); // Prints B::bar
return 0;
}
}
The new keyword actually creates a completely new member that only exists on that specific type.
For instance
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
The method exists on both types. When you use reflection and get the members of type Bar, you will actually find 2 methods called DoSomething() that look exactly the same. By using new you effectively hide the implementation in the base class, so that when classes derive from Bar (in my example) the method call to base.DoSomething() goes to Bar and not Foo.
Beyond just the technical details, I think using virtual/override communicates a lot of semantic information on the design. When you declare a method virtual, you indicate that you expect that implementing classes may want to provide their own, non-default implementations. Omitting this in a base class, likewise, declares the expectation that the default method ought to suffice for all implementing classes. Similarly, one can use abstract declarations to force implementing classes to provide their own implementation. Again, I think this communicates a lot about how the programmer expects the code to be used. If I were writing both the base and implementing classes and found myself using new I'd seriously rethink the decision not to make the method virtual in the parent and declare my intent specifically.
virtual / override tells the compiler that the two methods are related and that in some circumstances when you would think you are calling the first (virtual) method it's actually correct to call the second (overridden) method instead. This is the foundation of polymorphism.
(new SubClass() as BaseClass).VirtualFoo()
Will call the SubClass's overriden VirtualFoo() method.
new tells the compiler that you are adding a method to a derived class with the same name as a method in the base class, but they have no relationship to each other.
(new SubClass() as BaseClass).NewBar()
Will call the BaseClass's NewBar() method, whereas:
(new SubClass()).NewBar()
Will call the SubClass's NewBar() method.
The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding.
Check out the folllowing links for more information...
MSDN and Other
new keyword is for Hiding. - means you are hiding your method at runtime. Output will be based base class method.
override for overriding. - means you are invoking your derived class method with the reference of base class. Output will be based on derived class method.
My version of explanation comes from using properties to help understand the differences.
override is simple enough, right ? The underlying type overrides the parent's.
new is perhaps the misleading (for me it was). With properties it's easier to understand:
public class Foo
{
public bool GetSomething => false;
}
public class Bar : Foo
{
public new bool GetSomething => true;
}
public static void Main(string[] args)
{
Foo foo = new Bar();
Console.WriteLine(foo.GetSomething);
Bar bar = new Bar();
Console.WriteLine(bar.GetSomething);
}
Using a debugger you can notice that Foo foo has 2 GetSomething properties, as it actually has 2 versions of the property, Foo's and Bar's, and to know which one to use, c# "picks" the property for the current type.
If you wanted to use the Bar's version, you would have used override or use Foo foo instead.
Bar bar has only 1, as it wants completely new behavior for GetSomething.
Not marking a method with anything means: Bind this method using the object's compile type, not runtime type (static binding).
Marking a method with virtual means: Bind this method using the object's runtime type, not compile time type (dynamic binding).
Marking a base class virtual method with override in derived class means: This is the method to be bound using the object's runtime type (dynamic binding).
Marking a base class virtual method with new in derived class means: This is a new method, that has no relation to the one with the same name in the base class and it should be bound using object's compile time type (static binding).
Not marking a base class virtual method in the derived class means: This method is marked as new (static binding).
Marking a method abstract means: This method is virtual, but I will not declare a body for it and its class is also abstract (dynamic binding).
using System;
using System.Text;
namespace OverrideAndNew
{
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
// The following two calls do what you would expect. They call
// the methods that are defined in BaseClass.
bc.Method1();
bc.Method2();
// Output:
// Base - Method1
// Base - Method2
// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
dc.Method1();
dc.Method2();
// Output:
// Derived - Method1
// Derived - Method2
// The following two calls produce different results, depending
// on whether override (Method1) or new (Method2) is used.
bcdc.Method1();
bcdc.Method2();
// Output:
// Derived - Method1
// Base - Method2
}
}
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public virtual void Method2()
{
Console.WriteLine("Base - Method2");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
}

If derived class does not override the method,which version should be called?

I am trying understand the need of override and virtual in C#,so I wrote the following code:
using System;
namespace Override
{
class Base
{
public virtual void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
d.method();
}
}
}
And I was expecting "Derived method" to be called and printed.Then I wrote the following code without using virtual/override combination.
using System;
namespace Override
{
class Base
{
public void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
d.method();
}
}
}
And I got the same result i.e. "Derived method" called and printed.My question is if the code worked without virtual/override as I expected,what is the need of them? or am I missing something here?
In your source code, you are always doing simple inheritance without any polymorphic behavior. You are always created instance of derived class and assigning it to derived class instance variable.
DerivedClass d = new DerivedClass(); // here no polymorphism, and only inheritance is there
So When you will call method using class variable, it will always call DerivedClass method, no matter if the method is virtual or not in parent class.
In Polymorphism, your programs do not know the exact type of class on which you are calling the method (this concept is called late-binding). As in example below:
BaseClass b = new DerivedClass(); // here b is a base class instance but initiated using derived class
After calling b.method() it will do late binding and will show polymorphic behavior (only if the method has been set virtual in the base class)
NOTE: The virtual keyword delays binding to correct version of method to runtime and is core keywork to implement polyphorphism. So for exact polymorphic behavior, declare methods as virtual in parent class, and then in child class, ovverride that method.
virtual allows the correct version of the method to be chosen at runtime, based on information not available at compile time. Consider the following tweak to your example:
using System;
namespace Override
{
class Base
{
public virtual void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
Base b = d;
b.method();
}
}
}
With virtual/override, this code will display Derived method, as at runtime we can see that b is really a Derived instance. Without virtual/override, it will display Base method, as the declared type of b is Base.
Here is the test you are missing:
Base d = new Derived();
d.method(); // "Derived method"
Base b = new Base();
b.method(); // "Base method"
Also imagine if you had a collection of Base objects that were composed of different inherited objects. The virtual keyword allows those Base objects to understand what type they really are at runtime.
List<Base> collection = new List<Base>();
collection.Add(new Base());
collection.Add(new Derived()};
collection.Add(new Base());
foreach(Base b in collection)
{
b.method(); // will print out "Base" or "Derived" correctly
}
see the DIFFERENCE
class Base
{
public void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d;
d = new Derived();
d.method();
d = new Base();
d.method();
}
}
OUTPUT :
Derived method
Derived method
class Base
{
public virtual void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d;
d = new Derived();
d.method();
d = new Base();
d.method();
}
}
OUTPUT :
Derived method
Base method
Base class pointers can be used to point to object of the base class or any object derived from the base. So the need of virtual methods come into picture when base class object point to derived class
Base d = new Derived();
d.method(); // "Derived method"
The method 'method' on the Derived class will hide the implementation of the Base class which is why you got the messaged "Derived method".
There are many uses of virtual and abstract but one example is where you have functionality in the base class which may not fit all cases of classes that inherit from your base class. Using virtual allows another class to completely override that functionality and provide its own implementation.

C# - Keyword usage virtual+override vs. new

What are differences between declaring a method in a base type "virtual" and then overriding it in a child type using the "override" keyword as opposed to simply using the "new" keyword when declaring the matching method in the child type?
I always find things like this more easily understood with pictures:
Again, taking joseph daigle's code,
public class Foo
{
public /*virtual*/ bool DoSomething() { return false; }
}
public class Bar : Foo
{
public /*override or new*/ bool DoSomething() { return true; }
}
If you then call the code like this:
Foo a = new Bar();
a.DoSomething();
NOTE: The important thing is that our object is actually a Bar, but we are storing it in a variable of type Foo (this is similar to casting it)
Then the result will be as follows, depending on whether you used virtual/override or new when declaring your classes.
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
public class Test
{
public static void Main ()
{
Foo test = new Bar ();
Console.WriteLine (test.DoSomething ());
}
}
This prints false, if you used override it would have printed true.
(Base code taken from Joseph Daigle)
So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.
Here's some code to understand the difference in the behavior of virtual and non-virtual methods:
class A
{
public void foo()
{
Console.WriteLine("A::foo()");
}
public virtual void bar()
{
Console.WriteLine("A::bar()");
}
}
class B : A
{
public new void foo()
{
Console.WriteLine("B::foo()");
}
public override void bar()
{
Console.WriteLine("B::bar()");
}
}
class Program
{
static int Main(string[] args)
{
B b = new B();
A a = b;
a.foo(); // Prints A::foo
b.foo(); // Prints B::foo
a.bar(); // Prints B::bar
b.bar(); // Prints B::bar
return 0;
}
}
The new keyword actually creates a completely new member that only exists on that specific type.
For instance
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
The method exists on both types. When you use reflection and get the members of type Bar, you will actually find 2 methods called DoSomething() that look exactly the same. By using new you effectively hide the implementation in the base class, so that when classes derive from Bar (in my example) the method call to base.DoSomething() goes to Bar and not Foo.
Beyond just the technical details, I think using virtual/override communicates a lot of semantic information on the design. When you declare a method virtual, you indicate that you expect that implementing classes may want to provide their own, non-default implementations. Omitting this in a base class, likewise, declares the expectation that the default method ought to suffice for all implementing classes. Similarly, one can use abstract declarations to force implementing classes to provide their own implementation. Again, I think this communicates a lot about how the programmer expects the code to be used. If I were writing both the base and implementing classes and found myself using new I'd seriously rethink the decision not to make the method virtual in the parent and declare my intent specifically.
virtual / override tells the compiler that the two methods are related and that in some circumstances when you would think you are calling the first (virtual) method it's actually correct to call the second (overridden) method instead. This is the foundation of polymorphism.
(new SubClass() as BaseClass).VirtualFoo()
Will call the SubClass's overriden VirtualFoo() method.
new tells the compiler that you are adding a method to a derived class with the same name as a method in the base class, but they have no relationship to each other.
(new SubClass() as BaseClass).NewBar()
Will call the BaseClass's NewBar() method, whereas:
(new SubClass()).NewBar()
Will call the SubClass's NewBar() method.
The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding.
Check out the folllowing links for more information...
MSDN and Other
new keyword is for Hiding. - means you are hiding your method at runtime. Output will be based base class method.
override for overriding. - means you are invoking your derived class method with the reference of base class. Output will be based on derived class method.
My version of explanation comes from using properties to help understand the differences.
override is simple enough, right ? The underlying type overrides the parent's.
new is perhaps the misleading (for me it was). With properties it's easier to understand:
public class Foo
{
public bool GetSomething => false;
}
public class Bar : Foo
{
public new bool GetSomething => true;
}
public static void Main(string[] args)
{
Foo foo = new Bar();
Console.WriteLine(foo.GetSomething);
Bar bar = new Bar();
Console.WriteLine(bar.GetSomething);
}
Using a debugger you can notice that Foo foo has 2 GetSomething properties, as it actually has 2 versions of the property, Foo's and Bar's, and to know which one to use, c# "picks" the property for the current type.
If you wanted to use the Bar's version, you would have used override or use Foo foo instead.
Bar bar has only 1, as it wants completely new behavior for GetSomething.
Not marking a method with anything means: Bind this method using the object's compile type, not runtime type (static binding).
Marking a method with virtual means: Bind this method using the object's runtime type, not compile time type (dynamic binding).
Marking a base class virtual method with override in derived class means: This is the method to be bound using the object's runtime type (dynamic binding).
Marking a base class virtual method with new in derived class means: This is a new method, that has no relation to the one with the same name in the base class and it should be bound using object's compile time type (static binding).
Not marking a base class virtual method in the derived class means: This method is marked as new (static binding).
Marking a method abstract means: This method is virtual, but I will not declare a body for it and its class is also abstract (dynamic binding).
using System;
using System.Text;
namespace OverrideAndNew
{
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
// The following two calls do what you would expect. They call
// the methods that are defined in BaseClass.
bc.Method1();
bc.Method2();
// Output:
// Base - Method1
// Base - Method2
// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
dc.Method1();
dc.Method2();
// Output:
// Derived - Method1
// Derived - Method2
// The following two calls produce different results, depending
// on whether override (Method1) or new (Method2) is used.
bcdc.Method1();
bcdc.Method2();
// Output:
// Derived - Method1
// Base - Method2
}
}
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public virtual void Method2()
{
Console.WriteLine("Base - Method2");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
}

Categories

Resources