About virtual method in parent class C# [duplicate] - c#

This question already has answers here:
Overriding vs method hiding [duplicate]
(3 answers)
Closed 8 years ago.
I think child class can override parent method which is not virtual
class Parent {
public void hello() {
Console.WriteLine("Hello Parent");
}
}
class Child:Parent{
public void hello() {
Console.WriteLine("Hello Child");
}
static void Main() {
Parent p = new Child();
Child c = new Child();
p.hello(); // Hello Parent
c.hello(); // Hello Child
}
}
So what different between virtual and not virtual in a parent method ???

In C#, virtual methods support polymorphism, by using a combination of the virtual and override keywords. With the virtual keyword on the base class method and the override keyword on the method in the derived class, both methods are said to be virtual.
Methods that don’t have either the virtual or override keywords, or that have the new keyword, are said to be non-virtual.
When a virtual method is invoked on an object, the run-time type of the object is used to determine which implementation of the method to use.
When a non-virtual method is invoked on an object, the compile-time type of the object is used to determine which implementation of the method to use.
In this case, you can use the new keyword
public new void hello()
{
Console.WriteLine("Hello Child");
}
Text taken from here
Read more about when to use override and new keyword

There is a big difference. I suggest you read this and carefully go through the examples.
To summarize, what you're dealing with is the difference between method overriding vs method hiding.
Method overriding allows a base type to access the behavior of the derived type's overridden functionality. This is what you're doing when you use the override keyword on a derived type's method where the base type's method is marked with the virtual keyword. On the other hand, using the same method signature on a more derived where the base type's method is not marked as virtual is what's known as method hiding. You can actually do this without using the new keyword, but you will get a compiler warning.
Method hiding loses the polymorphic benefits that method overriding provides, in that the methods of the derived class will use the "new" behavior of the hidden method, but base class will continue to use the base class's version of the method. The results of method hiding can seem pretty unintuitive and typically the effects are undesirable in OOP, but it does have its place. For instance, one of my favorite uses of method hiding is to allow for easier unit testing of protected methods.
The following code example is taken directly from the first link and succinctly illustrates one of the ways which method overriding differs from method hiding:
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");
}
}

The method hello() in the child class not override the hello method in the parent class. Child method just hide the implementation in parent class

Only methods marked as virtual can be overridden. Others can be hidden (using the new keyword), which isn't the same thing at all.
class Parent
{
public virtual int MyMethod()
{
return 1;
}
}
class Child : Parent
{
public override int MyMethod()
{
return 2;
}
}
class OtherChild : Parent
{
public new int MyMethod()
{
return 3;
}
}
// ...
Parent p = new Parent();
Parent c = new Child();
Parent oc = new OtherChild();
int result;
result = p.MyMethod(); // will return 1
result = c.MyMethod(); // will return 2
result = oc.MyMethod(); // will return 1
In the example above notice that every variables are declared as Parent. Calling the MyMethod on the first will simply return the basic implementation. Calling it on the second one calls the override found in Child class. The third one, however, being declared Parent, doesn't know about the implementation of MyMethod within OtherChild class and calls the one it knows: in Parent.
If you want to learn more on polymorphism, I suggest you have a look at this article on Wikipedia:
Polymorphism (computer science)

problem is with your testing code, power of virtual comes this way (if you set your method to virtual):
Parent p = new Parent();
Parent c = new Child();
Console.WriteLine(p.hello()); //Prints Hello Parent
Console.WriteLine(c.hello()); //Prints Hello Child
if you keep it unvirtual, both lines would print hello parent
kinda real world example is this:
Vehicle p = new Vehicle();
Vehicle c = new Car();
Console.WriteLine(p.Drive()); //Prints "Default Vehicle"
Console.WriteLine(c.Drive()); //Prints "Car"

Related

C# new virtual method and as/is casts [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");
}
}
}

C# didnt call drived class function in polymorphism when pass parameter [duplicate]

Wondering what the difference is between the following:
Case 1: Base Class
public void DoIt();
Case 1: Inherited class
public new void DoIt();
Case 2: Base Class
public virtual void DoIt();
Case 2: Inherited class
public override void DoIt();
Both case 1 and 2 appear to have the same effect based on the tests I have run. Is there a difference, or a preferred way?
The override modifier may be used on
virtual methods and must be used on
abstract methods. This indicates for
the compiler to use the last defined
implementation of a method. Even if
the method is called on a reference to
the base class it will use the
implementation overriding it.
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public override void DoIt()
{
}
}
Base b = new Derived();
b.DoIt(); // Calls Derived.DoIt
will call Derived.DoIt if that overrides Base.DoIt.
The new modifier instructs the
compiler to use your child class implementation
instead of the parent class
implementation. Any code that is not
referencing your class but the parent
class will use the parent class
implementation.
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public new void DoIt()
{
}
}
Base b = new Derived();
Derived d = new Derived();
b.DoIt(); // Calls Base.DoIt
d.DoIt(); // Calls Derived.DoIt
Will first call Base.DoIt, then Derived.DoIt. They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.
Source: Microsoft blog
virtual: indicates that a method may be overriden by an inheritor
override: overrides the functionality of a virtual method in a base class, providing different functionality.
new: hides the original method (which doesn't have to be virtual), providing different functionality. This should only be used where it is absolutely necessary.
When you hide a method, you can still access the original method by up casting to the base class. This is useful in some scenarios, but dangerous.
In the first case you are hiding the definition in the parent class. This means that it will only be invoked when you are dealing with the object as the child class. If you cast the class to its parent type, the parent's method will be invoked. In the second instance, the method is overridden and will be invoked regardless of whether the object is cast as the child or parent class.
new means respect your REFERENCE type(left-hand side of =) , thereby running reference types's method. If redefined method doesn't have new keyword, it is behaved as it has. Moreover, it also known as non-polymorphic inheritance. That is,
“I’m making a brand new method in the derived class that has
absolutely nothing to do with any methods by the same name in the base
class.” - by said Whitaker
override, which must be used with virtual keyword in its base class, means respect your OBJECT type(right-hand side of =), thereby
running method overriden in regardless of reference type. Moreover, it also known as polymorphic inheritance.
My way to bear in mind both keywords that they are opposite of each other.
override: virtual keyword must be defined to override the method. The method using override keyword that regardless of reference type(reference of base class or derived class) if it is instantiated with base class, the method of base class runs. Otherwise, the method of derived class runs.
new: if the keyword is used by a method, unlike override keyword, the reference type is important. If it is instantiated with derived class and the reference type is base class, the method of base class runs. If it is instantiated with derived class and the reference type is derived class, the method of derived class runs. Namely, it is contrast of override keyword. En passant, if you forget or omit to add new keyword to the method, the compiler behaves by default as new keyword is used.
class A
{
public string Foo()
{
return "A";
}
public virtual string Test()
{
return "base test";
}
}
class B: A
{
public new string Foo()
{
return "B";
}
}
class C: B
{
public string Foo()
{
return "C";
}
public override string Test() {
return "derived test";
}
}
Call in main:
A AClass = new B();
Console.WriteLine(AClass.Foo());
B BClass = new B();
Console.WriteLine(BClass.Foo());
B BClassWithC = new C();
Console.WriteLine(BClassWithC.Foo());
Console.WriteLine(AClass.Test());
Console.WriteLine(BClassWithC.Test());
Output:
A
B
B
base test
derived test
New code example,
Play with code by commenting in one-by-one.
class X
{
protected internal /*virtual*/ void Method()
{
WriteLine("X");
}
}
class Y : X
{
protected internal /*override*/ void Method()
{
base.Method();
WriteLine("Y");
}
}
class Z : Y
{
protected internal /*override*/ void Method()
{
base.Method();
WriteLine("Z");
}
}
class Programxyz
{
private static void Main(string[] args)
{
X v = new Z();
//Y v = new Z();
//Z v = new Z();
v.Method();
}
try following: (case1)
((BaseClass)(new InheritedClass())).DoIt()
Edit: virtual+override are resolved at runtime (so override really overrides virtual methods), while new just create new method with the same name, and hides the old, it is resolved at compile time -> your compiler will call the method it 'sees'
All combinations of none, virtual, override, new and abstract:
In case 1 if you used call the DoIt() method of the inherited class while the type is declared as the base class you will see the action of the base class even.
/* Results
Class1
Base1
Class2
Class2
*/
public abstract class Base1
{
public void DoIt() { Console.WriteLine("Base1"); }
}
public class Class1 : Base1
{
public new void DoIt() { Console.WriteLine("Class1"); }
}
public abstract class Base2
{
public virtual void DoIt() { Console.WriteLine("Base2"); }
}
public class Class2 : Base2
{
public override void DoIt() { Console.WriteLine("Class2"); }
}
static void Main(string[] args)
{
var c1 = new Class1();
c1.DoIt();
((Base1)c1).DoIt();
var c2 = new Class2();
c2.DoIt();
((Base2)c2).DoIt();
Console.Read();
}
The difference between the two cases is that in case 1, the base DoIt method does not get overridden, just hidden. What this means is that depending on the type of the variable depends on which method will get called. For example:
BaseClass instance1 = new SubClass();
instance1.DoIt(); // Calls base class DoIt method
SubClass instance2 = new SubClass();
instance2.DoIt(); // Calls sub class DoIt method
This can be really confusing and results in non expected behaviour and should be avoided if possible. So the preferred way would be case 2.
I had the same question and it's really confusing,
you should consider that override and new keywords working only with objects of type base class and value of derived class. In this case only you'll see the effect of override and new:
So if you have class A and B, B inherits from A, then you instantiate an object like this:
A a = new B();
Now on calling methods will take its state into consideration.
Override: means that it extends the function of the method, then it uses the method in the derived class, whereas new tell the compiler to hide the method in the derived class and use the method in the base class instead.
Here is a very good sight to that subject:
https://msdn.microsoft.com/EN-US/library/ms173153%28v=VS.140,d=hv.2%29.aspx?f=255&MSPPError=-2147217396
The article below is in vb.net but I think the explanation about new vs overrides is very easy to grasp.
https://www.codeproject.com/articles/17477/the-dark-shadow-of-overrides
At some point in the article, there is this sentence:
In general, Shadows assumes the function associated with the type is
invoked, while Overrides assumes the object implementation is
executed.
The accepted answer to this question is perfect but I think this article provide good examples to add better meaning about the differences between these two keywords.
If keyword override is used in derive class then its override the parent method.
If Keyword new is used in derive class then derive method hided by parent method.
Out of all those, new is the most confusing. Through experimenting, the new keyword is like giving developers the option to override the inheriting class implementation with the base class implementation by explicitly defining the type. It is like thinking the other way around.
In the example below, the result will return "Derived result" until the type is explicitly defined as BaseClass test, only then "Base result" will be returned.
class Program
{
static void Main(string[] args)
{
var test = new DerivedClass();
var result = test.DoSomething();
}
}
class BaseClass
{
public virtual string DoSomething()
{
return "Base result";
}
}
class DerivedClass : BaseClass
{
public new string DoSomething()
{
return "Derived result";
}
}
The functional difference will not be show in these tests:
BaseClass bc = new BaseClass();
bc.DoIt();
DerivedClass dc = new DerivedClass();
dc.ShowIt();
In this exmample, the Doit that is called is the one you expect to be called.
In order to see the difference you have to do this:
BaseClass obj = new DerivedClass();
obj.DoIt();
You will see if you run that test that in the case 1 (as you defined it), the DoIt() in BaseClass is called, in case 2 (as you defined it), the DoIt() in DerivedClass is called.
new : It just hides the method of the base class, but you can access it if you want.
override: It's overriding the base class's method and you can't access it even if you want to.
Example
using System;
public class Program
{
public static void Main()
{
BaseClass test = new DerivedClass();
var result = test.DoSomething();
Console.WriteLine(result);
}
class BaseClass
{
public string DoSomething()
{
return "Base result";
}
}
class DerivedClass : BaseClass
{
public new string DoSomething()
{
return "Derived result";
}
}
}
Result: Base result
P.S. I copied and slightly changed the above example from the following link:
https://stackoverflow.com/a/45822233/10995103

Inheritance chain with overriding and shadowing [duplicate]

Wondering what the difference is between the following:
Case 1: Base Class
public void DoIt();
Case 1: Inherited class
public new void DoIt();
Case 2: Base Class
public virtual void DoIt();
Case 2: Inherited class
public override void DoIt();
Both case 1 and 2 appear to have the same effect based on the tests I have run. Is there a difference, or a preferred way?
The override modifier may be used on
virtual methods and must be used on
abstract methods. This indicates for
the compiler to use the last defined
implementation of a method. Even if
the method is called on a reference to
the base class it will use the
implementation overriding it.
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public override void DoIt()
{
}
}
Base b = new Derived();
b.DoIt(); // Calls Derived.DoIt
will call Derived.DoIt if that overrides Base.DoIt.
The new modifier instructs the
compiler to use your child class implementation
instead of the parent class
implementation. Any code that is not
referencing your class but the parent
class will use the parent class
implementation.
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public new void DoIt()
{
}
}
Base b = new Derived();
Derived d = new Derived();
b.DoIt(); // Calls Base.DoIt
d.DoIt(); // Calls Derived.DoIt
Will first call Base.DoIt, then Derived.DoIt. They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.
Source: Microsoft blog
virtual: indicates that a method may be overriden by an inheritor
override: overrides the functionality of a virtual method in a base class, providing different functionality.
new: hides the original method (which doesn't have to be virtual), providing different functionality. This should only be used where it is absolutely necessary.
When you hide a method, you can still access the original method by up casting to the base class. This is useful in some scenarios, but dangerous.
In the first case you are hiding the definition in the parent class. This means that it will only be invoked when you are dealing with the object as the child class. If you cast the class to its parent type, the parent's method will be invoked. In the second instance, the method is overridden and will be invoked regardless of whether the object is cast as the child or parent class.
new means respect your REFERENCE type(left-hand side of =) , thereby running reference types's method. If redefined method doesn't have new keyword, it is behaved as it has. Moreover, it also known as non-polymorphic inheritance. That is,
“I’m making a brand new method in the derived class that has
absolutely nothing to do with any methods by the same name in the base
class.” - by said Whitaker
override, which must be used with virtual keyword in its base class, means respect your OBJECT type(right-hand side of =), thereby
running method overriden in regardless of reference type. Moreover, it also known as polymorphic inheritance.
My way to bear in mind both keywords that they are opposite of each other.
override: virtual keyword must be defined to override the method. The method using override keyword that regardless of reference type(reference of base class or derived class) if it is instantiated with base class, the method of base class runs. Otherwise, the method of derived class runs.
new: if the keyword is used by a method, unlike override keyword, the reference type is important. If it is instantiated with derived class and the reference type is base class, the method of base class runs. If it is instantiated with derived class and the reference type is derived class, the method of derived class runs. Namely, it is contrast of override keyword. En passant, if you forget or omit to add new keyword to the method, the compiler behaves by default as new keyword is used.
class A
{
public string Foo()
{
return "A";
}
public virtual string Test()
{
return "base test";
}
}
class B: A
{
public new string Foo()
{
return "B";
}
}
class C: B
{
public string Foo()
{
return "C";
}
public override string Test() {
return "derived test";
}
}
Call in main:
A AClass = new B();
Console.WriteLine(AClass.Foo());
B BClass = new B();
Console.WriteLine(BClass.Foo());
B BClassWithC = new C();
Console.WriteLine(BClassWithC.Foo());
Console.WriteLine(AClass.Test());
Console.WriteLine(BClassWithC.Test());
Output:
A
B
B
base test
derived test
New code example,
Play with code by commenting in one-by-one.
class X
{
protected internal /*virtual*/ void Method()
{
WriteLine("X");
}
}
class Y : X
{
protected internal /*override*/ void Method()
{
base.Method();
WriteLine("Y");
}
}
class Z : Y
{
protected internal /*override*/ void Method()
{
base.Method();
WriteLine("Z");
}
}
class Programxyz
{
private static void Main(string[] args)
{
X v = new Z();
//Y v = new Z();
//Z v = new Z();
v.Method();
}
try following: (case1)
((BaseClass)(new InheritedClass())).DoIt()
Edit: virtual+override are resolved at runtime (so override really overrides virtual methods), while new just create new method with the same name, and hides the old, it is resolved at compile time -> your compiler will call the method it 'sees'
All combinations of none, virtual, override, new and abstract:
In case 1 if you used call the DoIt() method of the inherited class while the type is declared as the base class you will see the action of the base class even.
/* Results
Class1
Base1
Class2
Class2
*/
public abstract class Base1
{
public void DoIt() { Console.WriteLine("Base1"); }
}
public class Class1 : Base1
{
public new void DoIt() { Console.WriteLine("Class1"); }
}
public abstract class Base2
{
public virtual void DoIt() { Console.WriteLine("Base2"); }
}
public class Class2 : Base2
{
public override void DoIt() { Console.WriteLine("Class2"); }
}
static void Main(string[] args)
{
var c1 = new Class1();
c1.DoIt();
((Base1)c1).DoIt();
var c2 = new Class2();
c2.DoIt();
((Base2)c2).DoIt();
Console.Read();
}
The difference between the two cases is that in case 1, the base DoIt method does not get overridden, just hidden. What this means is that depending on the type of the variable depends on which method will get called. For example:
BaseClass instance1 = new SubClass();
instance1.DoIt(); // Calls base class DoIt method
SubClass instance2 = new SubClass();
instance2.DoIt(); // Calls sub class DoIt method
This can be really confusing and results in non expected behaviour and should be avoided if possible. So the preferred way would be case 2.
I had the same question and it's really confusing,
you should consider that override and new keywords working only with objects of type base class and value of derived class. In this case only you'll see the effect of override and new:
So if you have class A and B, B inherits from A, then you instantiate an object like this:
A a = new B();
Now on calling methods will take its state into consideration.
Override: means that it extends the function of the method, then it uses the method in the derived class, whereas new tell the compiler to hide the method in the derived class and use the method in the base class instead.
Here is a very good sight to that subject:
https://msdn.microsoft.com/EN-US/library/ms173153%28v=VS.140,d=hv.2%29.aspx?f=255&MSPPError=-2147217396
The article below is in vb.net but I think the explanation about new vs overrides is very easy to grasp.
https://www.codeproject.com/articles/17477/the-dark-shadow-of-overrides
At some point in the article, there is this sentence:
In general, Shadows assumes the function associated with the type is
invoked, while Overrides assumes the object implementation is
executed.
The accepted answer to this question is perfect but I think this article provide good examples to add better meaning about the differences between these two keywords.
If keyword override is used in derive class then its override the parent method.
If Keyword new is used in derive class then derive method hided by parent method.
Out of all those, new is the most confusing. Through experimenting, the new keyword is like giving developers the option to override the inheriting class implementation with the base class implementation by explicitly defining the type. It is like thinking the other way around.
In the example below, the result will return "Derived result" until the type is explicitly defined as BaseClass test, only then "Base result" will be returned.
class Program
{
static void Main(string[] args)
{
var test = new DerivedClass();
var result = test.DoSomething();
}
}
class BaseClass
{
public virtual string DoSomething()
{
return "Base result";
}
}
class DerivedClass : BaseClass
{
public new string DoSomething()
{
return "Derived result";
}
}
The functional difference will not be show in these tests:
BaseClass bc = new BaseClass();
bc.DoIt();
DerivedClass dc = new DerivedClass();
dc.ShowIt();
In this exmample, the Doit that is called is the one you expect to be called.
In order to see the difference you have to do this:
BaseClass obj = new DerivedClass();
obj.DoIt();
You will see if you run that test that in the case 1 (as you defined it), the DoIt() in BaseClass is called, in case 2 (as you defined it), the DoIt() in DerivedClass is called.
new : It just hides the method of the base class, but you can access it if you want.
override: It's overriding the base class's method and you can't access it even if you want to.
Example
using System;
public class Program
{
public static void Main()
{
BaseClass test = new DerivedClass();
var result = test.DoSomething();
Console.WriteLine(result);
}
class BaseClass
{
public string DoSomething()
{
return "Base result";
}
}
class DerivedClass : BaseClass
{
public new string DoSomething()
{
return "Derived result";
}
}
}
Result: Base result
P.S. I copied and slightly changed the above example from the following link:
https://stackoverflow.com/a/45822233/10995103

How to achieve polymorphism in C#

I am new to C#. I was trying to check that how polymorphism could be acheived in C# and I got confused that which one way of doing is achieving polymorphism . I am using the code given below and the output is A's method .
class A
{
public void Display()
{
Console.WriteLine("A's Method");
}
}
class B : A
{
public void Display()
{
Console.WriteLine("B's Method");
}
}
class Polymorphism
{
public static void Main(string[] args)
{
A a = new B();
a.Display();
Console.ReadKey();
}
}
But when I define Display() method as given below then output Method of B is called .
class A
{
public virtual void Display()
{
Console.WriteLine("A's Method");
}
}
class B : A
{
public override void Display()
{
Console.WriteLine("B's Method");
}
}
So By what way I am achieving Polymorphism and what is the difference between both of the way and which one should be preferable for overriding. Any help would be appreciable.
Virtual methods provide polymorphism, in that subclasses can override behavior. If you don't use virtual methods all you have are types that inherit what is defined in other types, but can't replace these inherited behaviors with new ones.
In the first case, A's method is called because you have a reference to an A, and non-virtual methods are resolved at compile time. The B object is allowed to be referenced by an A variable because B is-a A. (Note that downcasting the object and calling the result would invoke B's method: ((B)a).Display();.)
In the second case, B's method is called because the method is virtual, and virtual methods are resolved at run time, based on the actual type of the object, not the type of reference it happens to be stored in.
Simply put, Polymorphism is when you can treat a derived object as if it were an ancestor object, and have all derived functionality function correctly.
In your first example, you are hiding the ancestor method, so if you treat the derived object as an ancestor then it behaves as ancestor. This is not polymorphic.
In the second example, you are overriding the ancestor method, so when you treat the object as an ancestor it still behaves like the derived object. This is polymorphic.
While it's a simple concept, there are a lot of not so simple side-effects and conditions that go along with it. For example, see the Liskov Substitution Principle (which I won't go into here). There are other principles and theories at play as well. But, it's enough to understand that polymorphism in C# is achieved primarily via inheritance (although it can also be achieved via ducktyping with dynamic objects and with generic typing of generics).
There are also several types of polymorphism... see the Wikipedia entry for more:
http://en.wikipedia.org/wiki/Polymorphism_(computer_science)
In one case you are doing method hiding and in another you are overriding it.Don't hesitate to take help of google,you'll get very useful articles or answers.Even on SO,you'll get many similar questions.
class A
{
public void Display()
{
Console.WriteLine("A's Method");
}
}
class B : A
{
public void Display()
{
Console.WriteLine("B's Method");
}
}
In the above example,you are doing shadowing or method hiding.You can get the even the same result if you use new keyword like in below code.if you use don't write override in method of child class, the method in the derived class doesn't override the method in the base class, it merely hides it.
public new void Display()
{
Console.WriteLine("B's Method");
}
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.So to aceive overriding you have to use override keyword which you are using in second example.
Simply put, if a method is not overriding the derived method, it is hiding it.An override method provides a new implementation of a member that is inherited from a base class.
You can also check here on MSDN when to do method hiding or when to do overriding.
Based on discussion on comment section,i am attaching below code.Hope it'll help you.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
A a=new A();
a.Display();//Parent's Method
B b =new B();
b.Display();//Child's Method
**A ab = new B();
ab.Display();//Parent's Method**
Console.ReadKey();
Parent parent = new Parent();
parent.Display();//Parent's Method
Child child = new Child();
child.Display();//Child's Method
**Parent ParentChild = new Child();
ParentChild.Display();//Child's Method**
Console.ReadKey();
}
class A
{
public virtual void Display()
{
Console.WriteLine("Parent's Method");
}
}
class B : A
{
public void Display()
{
Console.WriteLine("Child's Method");
}
}
class Parent
{
public virtual void Display()
{
Console.WriteLine("Parent's Method");
}
}
class Child : Parent
{
public override void Display()
{
Console.WriteLine("Child's Method");
}
}
}
}

virtual keyword in c#

I have knowledge of Java and have been learning C# for the last couple of days. Now I have come across the "virtual" keyword which, as suggested at this link, is used to allow the corresponding methods, properties etc. to be overriden in the subclasses. Now I think we can override methods even without using the "virtual" keyword. Then why it is necessary?
You need the virtual keyword if you really want to override methods in sub classes. Otherwise the base implementation will be hidden by the new implementation, just as if you had declared it with the new keyword.
Hiding the methods by "overriding" them without the base method being declared virtual leaves you without polymorphism, that means: if you "cast" a specialized version to the "base" version and call a method, always the base classes implementation will be used instead of the overridden version - which is not what you'd expect.
Example:
class A
{
public void Show() { Console.WriteLine("A"); }
}
class B : A
{
public void Show() { Console.WriteLine("B"); }
}
A a = new A();
B b = new B();
a.Show(); // "A"
b.Show(); // "B"
A a1 = b;
a1.Show(); // "A"!!!
virtual is a way of defining that a method has a default implementation, but that that implementation may be overriden in a child class. Other than by using virtual, you cannot override a method directly without using the new keyword (which is generally bad practice).
A good example of the implementation of virtual is the ToString() method. Every object in C# is guaranteed to be able to call ToString() because every object inherits from the base System.Object class, which contains a virtual method ToString(). Derived classes can override this however, and provide their own implementation which may be more useful to the users of the object.
Update: I recently wrote a blog post which goes into this topic in a bit of depth. Check it out here.
Now I think we can override methods even without using the "virtual" keyword.
No, you can't. Contrary to Java, in C# members are sealed by default and you cannot override them unless you marked them with the virtual keyword.
Take a look at this example:
void Main()
{
var o1 = new S();
Console.WriteLine(((B)o1).m1());
}
public class B
{
public virtual string m1() {
return "m1";
}
}
public class S : B
{
override public string m1() {
return "overridden m1";
}
}
In this example the subclass S is instantiated and assigned to object variable o1.
In the Console.WriteLine statement's parameter it is being cast into the base class B, then method m1 is called.
Because we have used virtual in the base class B and override in the subclass S, we're getting
overridden m1
as output. If you remove virtual in the method declaration of m1 in B and override in the subclass S then you're getting
m1
as output, which means that the cast also has the effect that the original declaration of method m1 in the base class B is used.
N.B. If you're using the new keyword in subclass S, such as
new public string m1() {
return "overridden m1";
}
assuming that the virtual keyword in the base class B is absent, you're getting the output
m1
as well. If you would not cast it to B, the new method would be used. This is called shadowing (or hiding) a method (the original method of the base class).
Summary:
To override a method, which should be effective also if you cast to the base class, use the virtual keyword in the base class and override in the sub class.
If you intend to override the method, which should be active in the sub class only, use the new keyword in the sub classes method declaration. As you have seen it works also without it, but it is better if it is there so everyone knows that this is a new version of the method.
virtual / override will allow the derived class to override the base function if the derived class is instantiated as the Base class.
Example:
class A
{
public virtual void Show() { Console.WriteLine("A"); }
}
class B : A
{
public override void Show() { Console.WriteLine("B"); }
}
A a = new A();
B b = new B();
a.Show();
b.Show();
A a1 = b;
a1.Show(); // here is the test!!!
B b1 = new B();
b.Show();
With virtual / override :
A
B
B
B
After removing virtual / override keywords (or simply removing override):
A
B
A
B

Categories