Reputation:
Consider this code:
class Program
{
static void Main(string[] args)
{
Person person = new Teacher();
person.ShowInfo();
Console.ReadLine();
}
}
public class Person
{
public void ShowInfo()
{
Console.WriteLine("I am Person");
}
}
public class Teacher : Person
{
public new void ShowInfo()
{
Console.WriteLine("I am Teacher");
}
}
When I run this code, the following is outputted:
I am Person
However, you can see that it is an instance of Teacher
, not of Person
. Why does the code do that?
Upvotes: 153
Views: 71093
Reputation: 123
class Program
{
static void Main(string[] args)
{
AA aa = new CC();
aa.Print();
}
}
public class AA {public virtual void Print() => WriteLine("AA");}
public class BB : AA {public override void Print() => WriteLine("BB");}
public class DD : BB {public override void Print() => WriteLine("DD");}
public class CC : DD {new public void Print() => WriteLine("CC");}
OutPut - DD
For those who wants to know how CLR is internally calling the new and virtual methods in C#.
When new keyword is used a new-slot of memory is get allocated for CC.Print()
and it will not over-ride the base class memory-slot as derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
When override is used the memory is being override by derived class member, in this case by AA.Print()
slot over-ride by BB.Print()
; BB.Print()
is over-ride by DD.Print()
.
When we call AA aa = new CC()
; compiler will create new slot of memmory for CC.Print()
but when it cast as AA, then as per Vtable Map, AA overridable object DD is called.
Reference - c# - Exact difference between overriding and hiding - Stack Overflow .NET Framework Internals: How the CLR Creates Runtime Objects | Microsoft Docs
Upvotes: 0
Reputation: 2557
I would like to add a couple of more examples to expand on the info around this. Hope this helps too:
Here is a code sample that clears the air around what happens when a derived type is assigned to a base type. Which methods are available and the difference between overridden and hidden methods in this context.
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
A a = new A();
a.foo(); // A.foo()
a.foo2(); // A.foo2()
a = new B();
a.foo(); // B.foo()
a.foo2(); // A.foo2()
//a.novel() is not available here
a = new C();
a.foo(); // C.foo()
a.foo2(); // A.foo2()
B b1 = (B)a;
b1.foo(); // C.foo()
b1.foo2(); // B.foo2()
b1.novel(); // B.novel()
Console.ReadLine();
}
}
class A
{
public virtual void foo()
{
Console.WriteLine("A.foo()");
}
public void foo2()
{
Console.WriteLine("A.foo2()");
}
}
class B : A
{
public override void foo()
{
// This is an override
Console.WriteLine("B.foo()");
}
public new void foo2() // Using the 'new' keyword doesn't make a difference
{
Console.WriteLine("B.foo2()");
}
public void novel()
{
Console.WriteLine("B.novel()");
}
}
class C : B
{
public override void foo()
{
Console.WriteLine("C.foo()");
}
public new void foo2()
{
Console.WriteLine("C.foo2()");
}
}
}
Another little anomaly is that, for the following line of code:
A a = new B();
a.foo();
The VS compiler (intellisense) would show a.foo() as A.foo().
Hence, it is clear that when a more derived type is assigned to a base type, the 'base type' variable acts as the base type until a method that is overridden in a derived type is referenced. This may become a little counter-intuitive with hidden methods or methods with the same name (but not overridden) between the parent and child types.
This code sample should help delineate these caveats!
Upvotes: 4
Reputation: 1318
Might be too late... But the question is simple and the answer should have the same level of complexity.
In your code variable person doesn't know anything about Teacher.ShowInfo(). There is no way to call last method from base class reference, because it's not virtual.
There is useful approach to inheritance - try to imagine what do you want to say with your code hierarchy. Also try to imagine what does one or another tool says about itself. E.g. if you add virtual function into a base class you suppose: 1. it can have default implementation; 2. it might be reimplemented in derived class. If you add abstract function it means only one thing - subclass must create an implementation. But in case you have plain function - you do not expect anyone to change its implementation.
Upvotes: 1
Reputation: 1
LinQPad sample to launch blindly and reduce duplication of code Which I think is what you were trying to do.
void Main()
{
IEngineAction Test1 = new Test1Action();
IEngineAction Test2 = new Test2Action();
Test1.Execute("Test1");
Test2.Execute("Test2");
}
public interface IEngineAction
{
void Execute(string Parameter);
}
public abstract class EngineAction : IEngineAction
{
protected abstract void PerformAction();
protected string ForChildren;
public void Execute(string Parameter)
{ // Pretend this method encapsulates a
// lot of code you don't want to duplicate
ForChildren = Parameter;
PerformAction();
}
}
public class Test1Action : EngineAction
{
protected override void PerformAction()
{
("Performed: " + ForChildren).Dump();
}
}
public class Test2Action : EngineAction
{
protected override void PerformAction()
{
("Actioned: " + ForChildren).Dump();
}
}
Upvotes: 0
Reputation: 1
Building on Keith S.'s excellent demonstration and every one else's quality answers and for the sake of uber completeness lets go ahead and toss explicit interface implementations in to demonstrate how that works. Consider the below:
namespace LinqConsoleApp {
class Program
{
static void Main(string[] args)
{
Person person = new Teacher();
Console.Write(GetMemberName(() => person) + ": ");
person.ShowInfo();
Teacher teacher = new Teacher();
Console.Write(GetMemberName(() => teacher) + ": ");
teacher.ShowInfo();
IPerson person1 = new Teacher();
Console.Write(GetMemberName(() => person1) + ": ");
person1.ShowInfo();
IPerson person2 = (IPerson)teacher;
Console.Write(GetMemberName(() => person2) + ": ");
person2.ShowInfo();
Teacher teacher1 = (Teacher)person1;
Console.Write(GetMemberName(() => teacher1) + ": ");
teacher1.ShowInfo();
Person person4 = new Person();
Console.Write(GetMemberName(() => person4) + ": ");
person4.ShowInfo();
IPerson person3 = new Person();
Console.Write(GetMemberName(() => person3) + ": ");
person3.ShowInfo();
Console.WriteLine();
Console.ReadLine();
}
private static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}
interface IPerson
{
void ShowInfo();
}
public class Person : IPerson
{
public void ShowInfo()
{
Console.WriteLine("I am Person == " + this.GetType());
}
void IPerson.ShowInfo()
{
Console.WriteLine("I am interface Person == " + this.GetType());
}
}
public class Teacher : Person, IPerson
{
public void ShowInfo()
{
Console.WriteLine("I am Teacher == " + this.GetType());
}
}
}
Here's the output:
person: I am Person == LinqConsoleApp.Teacher
teacher: I am Teacher == LinqConsoleApp.Teacher
person1: I am Teacher == LinqConsoleApp.Teacher
person2: I am Teacher == LinqConsoleApp.Teacher
teacher1: I am Teacher == LinqConsoleApp.Teacher
person4: I am Person == LinqConsoleApp.Person
person3: I am interface Person == LinqConsoleApp.Person
Two things to note:
The Teacher.ShowInfo() method omits the the new keyword. When new is omitted the method behavior is the same as if the new keyword was explicitly defined.
You can only use the override keyword in conjunction with the virtual key word. The base class method must be virtual. Or abstract in which case the class must also be abstract.
person gets the the base implementation of ShowInfo because the Teacher class can't override the base implementation (no virtual declaration) and person is .GetType(Teacher) so it hides the the Teacher class's implementation.
teacher gets the derived Teacher implementation of ShowInfo because teacher because it is Typeof(Teacher) and it's not on the Person inheritance level.
person1 gets the derived Teacher implementation because it is .GetType(Teacher) and the implied new keyword hides the base implementation.
person2 also gets the derived Teacher implementation even though it does implement IPerson and it gets an explicit cast to IPerson. This is again because the Teacher class does not explicitly implement the IPerson.ShowInfo() method.
teacher1 also gets the derived Teacher implementation because it is .GetType(Teacher).
Only person3 gets the IPerson implementation of ShowInfo because only the Person class explicitly implements the method and person3 is an instance of the IPerson type.
In order to explicitly implement an interface you must declare a var instance of the target interface type and a class must explicitly implement (fully qualify) the interface member(s).
Notice not even person4 gets the IPerson.ShowInfo implementation. This is because even though person4 is .GetType(Person) and even though Person implements IPerson, person4 is not an instance of IPerson.
Upvotes: 0
Reputation: 71565
I want to build off of Achratt's answer. For completeness, the difference is that the OP is expecting the new
keyword in the derived class's method to override the base class method. What it actually does is hide the base class method.
In C#, as another answer mentioned, traditional method overriding must be explicit; the base class method must be marked as virtual
and the derived class must specifically override
the base class method. If this is done, then it doesn't matter whether the object is treated as being an instance of the base class or derived class; the derived method is found and called. This is done in a similar fashion as in C++; a method marked "virtual" or "override", when compiled, is resolved "late" (at runtime) by determining the referenced object's actual type, and traversing the object hierarchy downward along the tree from the variable type to the actual object type, to find the most derived implementation of the method defined by the variable type.
This differs from Java, which allows "implicit overrides"; for instance methods (non-static), simply defining a method of the same signature (name and number/type of parameters) will cause the subclass to override the superclass.
Because it's often useful to extend or override the functionality of a non-virtual method you do not control, C# also includes the new
contextual keyword. The new
keyword "hides" the parent method instead of overriding it. Any inheritable method can be hidden whether it's virtual or not; this allows you, the developer, to leverage the members you want to inherit from a parent, without having to work around the ones you don't, while still allowing you to present the same "interface" to consumers of your code.
Hiding works similarly to overriding from the perspective of a person using your object at or below the level of inheritance at which the hiding method is defined. From the question's example, a coder creating a Teacher and storing that reference in a variable of the Teacher type will see the behavior of the ShowInfo() implementation from Teacher, which hides the one from Person. However, someone working with your object in a collection of Person records (as you are) will see the behavior of the Person implementation of ShowInfo(); because Teacher's method doesn't override its parent (which would also require Person.ShowInfo() to be virtual), code working at the Person level of abstraction won't find the Teacher implementation and won't use it.
In addition, not only will the new
keyword do this explicitly, C# allows implicit method hiding; simply defining a method with the same signature as a parent class method, without override
or new
, will hide it (though it will produce a compiler warning or a complaint from certain refactoring assistants like ReSharper or CodeRush). This is the compromise C#'s designers came up with between C++'s explicit overrides vs Java's implicit ones, and while it's elegant, it doesn't always produce the behavior you would expect if you come from a background in either of the older languages.
Here's the new stuff: This gets complex when you combine the two keywords in a long inheritance chain. Consider the following:
class Foo { public virtual void DoFoo() { Console.WriteLine("Foo"); } }
class Bar:Foo { public override sealed void DoFoo() { Console.WriteLine("Bar"); } }
class Baz:Bar { public virtual void DoFoo() { Console.WriteLine("Baz"); } }
class Bai:Baz { public override void DoFoo() { Console.WriteLine("Bai"); } }
class Bat:Bai { public new void DoFoo() { Console.WriteLine("Bat"); } }
class Bak:Bat { }
Foo foo = new Foo();
Bar bar = new Bar();
Baz baz = new Baz();
Bai bai = new Bai();
Bat bat = new Bat();
foo.DoFoo();
bar.DoFoo();
baz.DoFoo();
bai.DoFoo();
bat.DoFoo();
Console.WriteLine("---");
Foo foo2 = bar;
Bar bar2 = baz;
Baz baz2 = bai;
Bai bai2 = bat;
Bat bat2 = new Bak();
foo2.DoFoo();
bar2.DoFoo();
baz2.DoFoo();
bai2.DoFoo();
Console.WriteLine("---");
Foo foo3 = bak;
Bar bar3 = bak;
Baz baz3 = bak;
Bai bai3 = bak;
Bat bat3 = bak;
foo3.DoFoo();
bar3.DoFoo();
baz3.DoFoo();
bai3.DoFoo();
bat3.DoFoo();
Output:
Foo
Bar
Baz
Bai
Bat
---
Bar
Bar
Bai
Bai
Bat
---
Bar
Bar
Bai
Bai
Bat
The first set of five is all to be expected; because each level has an implementation, and is referenced as an object of the same type as was instantiated, the runtime resolves each call to the inheritance level referenced by the variable type.
The second set of five is the result of assigning each instance to a variable of the immediate parent type. Now, some differences in behavior shake out; foo2
, which is actually a Bar
cast as a Foo
, will still find the more derived method of the actual object type Bar. bar2
is a Baz
, but unlike with foo2
, because Baz doesn't explicitly override Bar's implementation (it can't; Bar sealed
it), it's not seen by the runtime when looking "top-down", so Bar's implementation is called instead. Notice that Baz doesn't have to use the new
keyword; you'll get a compiler warning if you omit the keyword, but the implied behavior in C# is to hide the parent method. baz2
is a Bai
, which overrides Baz
's new
implementation, so its behavior is similar to foo2
's; the actual object type's implementation in Bai is called. bai2
is a Bat
, which again hides its parent Bai
's method implementation, and it behaves the same as bar2
even though Bai's implementation isn't sealed, so theoretically Bat could have overridden instead of hidden the method. Finally, bat2
is a Bak
, which has no overriding implementation of either kind, and simply uses that of its parent.
The third set of five illustrates the full top-down resolution behavior. Everything is actually referencing an instance of the most derived class in the chain, Bak
, but resolution at every level of variable type is performed by starting at that level of the inheritance chain and drilling down to the most derived explicit override of the method, which are those in Bar
, Bai
, and Bat
. Method hiding thus "breaks" the overriding inheritance chain; you have to be working with the object at or below the level of inheritance that hides the method in order for the hiding method to be used. Otherwise, the hidden method is "uncovered" and used instead.
Upvotes: 7
Reputation: 1394
Please read about polymorphism in C#: Polymorphism (C# Programming Guide)
This is an example from there:
When the new keyword is used, the new class members are called instead of the base class members that have been replaced. Those base class members are called hidden members. Hidden class members can still be called if an instance of the derived class is cast to an instance of the base class. For example:
DerivedClass B = new DerivedClass();
B.DoWork(); // Calls the new method.
BaseClass A = (BaseClass)B;
A.DoWork(); // Calls the old method.
Upvotes: 4
Reputation: 11606
There's a difference between new
and virtual
/override
.
You can imagine, that a class, when instantiated, is nothing more than a table of pointers, pointing to the actual implementation of its methods. The following image should visualize this pretty well:
Now there are different ways, a method can be defined. Each behaves different when it is used with inheritance. The standard way always works like the image above illustrates. If you want to change this behavior, you can attach different keywords to your method.
The first one is abstract
. abstract
methods simply point to nowhere:
If your class contains abstract members, it also needs to be marked as abstract
, otherwise the compiler will not compile your application. You cannot create instances of abstract
classes, but you can inherit from them and create instances of your inherited classes and access them using the base class definition. In your example this would look like:
public abstract class Person
{
public abstract void ShowInfo();
}
public class Teacher : Person
{
public override void ShowInfo()
{
Console.WriteLine("I am a teacher!");
}
}
public class Student : Person
{
public override void ShowInfo()
{
Console.WriteLine("I am a student!");
}
}
If called, the behavior of ShowInfo
varies, based on the implementation:
Person person = new Teacher();
person.ShowInfo(); // Shows 'I am a teacher!'
person = new Student();
person.ShowInfo(); // Shows 'I am a student!'
Both, Student
s and Teacher
s are Person
s, but they behave different when they are asked to prompt information about themselves. However, the way to ask them to prompt their information, is the same: Using the Person
class interface.
So what happens behind the scenes, when you inherit from Person
? When implementing ShowInfo
, the pointer is not pointing to nowhere any longer, it now points to the actual implementation! When creating a Student
instance, it points to Student
s ShowInfo
:
The second way is to use virtual
methods. The behavior is the same, except you are providing an optional default implementation in your base class. Classes with virtual
members can be instanciated, however inherited classes can provide different implementations. Here's what your code should actually look like to work:
public class Person
{
public virtual void ShowInfo()
{
Console.WriteLine("I am a person!");
}
}
public class Teacher : Person
{
public override void ShowInfo()
{
Console.WriteLine("I am a teacher!");
}
}
The key difference is, that the base member Person.ShowInfo
isn't pointing to nowhere any longer. This is also the reason, why you can create instances of Person
(and thus it does not need to be marked as abstract
any longer):
You should notice, that this doesn't look different from the first image for now. This is because the virtual
method is pointing to an implementation "the standard way". Using virtual
, you can tell Persons
, that they can (not must) provide a different implementation for ShowInfo
. If you provide a different implementation (using override
), like I did for the Teacher
above, the image would look the same as for abstract
. Imagine, we did not provide a custom implementation for Student
s:
public class Student : Person
{
}
The code would be called like this:
Person person = new Teacher();
person.ShowInfo(); // Shows 'I am a teacher!'
person = new Student();
person.ShowInfo(); // Shows 'I am a person!'
And the image for Student
would look like this:
new
is more a hack around this. You can provide methods in generalized classes, that have the same names as methods in the base class/interface. Both point to their own, custom implementation:
The implementation looks like the one, you provided. The behavior differs, based on the way you access the method:
Teacher teacher = new Teacher();
Person person = (Person)teacher;
teacher.ShowInfo(); // Prints 'I am a teacher!'
person.ShowInfo(); // Prints 'I am a person!'
This behavior can be wanted, but in your case it is misleading.
I hope this makes things clearer to understand for you!
Upvotes: 378
Reputation: 58
I wrote the same code as u have mentioned above in java except some changes and it worked fine as excepted. Method of the base class is overridden and so output displayed is "I am Teacher".
Reason: As we are creating a reference of the base class (which is capable of having referring instance of the derived class) which is actually containing the reference of the derived class. And as we know that the instance always look upon its methods first if it finds it there it executes it, and if it doesn't find the definition there it goes up in the hierarchy.
public class inheritance{
public static void main(String[] args){
Person person = new Teacher();
person.ShowInfo();
}
}
class Person{
public void ShowInfo(){
System.out.println("I am Person");
}
}
class Teacher extends Person{
public void ShowInfo(){
System.out.println("I am Teacher");
}
}
Upvotes: 0
Reputation: 3952
The new keyword tell that the method in the current class will only work if you have an instance of the class Teacher stored in a variable of type Teacher. Or you can trigger it using castings: ((Teacher)Person).ShowInfo()
Upvotes: 2
Reputation: 148110
You have to make the method virtual and you have to override the function in the child class, in order to call the method of class object you put in parent class reference.
public class Person
{
public virtual void ShowInfo()
{
Console.WriteLine("I am Person");
}
}
public class Teacher : Person
{
public override void ShowInfo()
{
Console.WriteLine("I am Teacher");
}
}
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member. By default, methods are non-virtual. You cannot override a non-virtual method. You cannot use the virtual modifier with the static, abstract, private or override modifiers, MSDN.
You are using new key word instead of override, this is what new does
If the method in the derived class is not preceded by new or override keywords, the compiler will issue a warning and the method will behave as if the new keyword were present.
If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class, This MSDN article explains it very well.
We have early binding at compile time for normal method (not virtual) which is the currrent case the compiler will bind call to method of base class that is method of reference type (base class) instead of the object is held in the referece of base class i.e. derived class object. This is because ShowInfo
is not a virtual method. The late binding is performed at runtime for (virtual / overridden method) using virtual method table (vtable).
For a normal function, the compiler can work out the numeric location of it in memory. Then it when the function is called it can generate an instruction to call the function at this address.
For an object that has any virtual methods, the compiler will generate a v-table. This is essentially an array that contains the addresses of the virtual methods. Every object that has a virtual method will contain a hidden member generated by the compiler that is the address of the v-table. When a virtual function is called, the compiler will work out what the position is of the appropriate method in the v-table. It will then generate code to look in the objects v-table and call the virtual method at this position, Reference.
Upvotes: 26
Reputation: 1116
Just wanted to give a brief answer -
You should use virtual
and override
in classes that could be overridden. Use virtual
for methods that can be overriden by child classes and use override
for methods that should override such virtual
methods.
Upvotes: 0
Reputation:
Subtype polymorphism in C# uses explicit virtuality, similar to C++ but unlike Java. This means that you explicitly have to mark methods as overridable (i.e. virtual
). In C# you also have to explicitly mark overriding methods as overriding (i.e. override
) to prevent typos.
public class Person
{
public virtual void ShowInfo()
{
Console.WriteLine("I am Person");
}
}
public class Teacher : Person
{
public override void ShowInfo()
{
Console.WriteLine("I am Teacher");
}
}
In the code in your question, you use new
, which does shadowing instead of overriding. Shadowing merely affects the compile-time semantics rather than the runtime semantics, hence the unintended output.
Upvotes: 45
Reputation: 43
The type of variable 'teacher' here is typeof(Person)
and this type does not know anything about Teacher class and does not try to look for any methods in derived types. To call method of Teacher class you should cast your variable: (person as Teacher).ShowInfo()
.
To call specific method based on value type you should use keyword 'virtual' in your base class and override virtual methods in derived classes. This approach allows to implement derived classes with or without overriding of virtual methods. Methods of base class will be called for types without overided virtuals.
public class Program
{
private static void Main(string[] args)
{
Person teacher = new Teacher();
teacher.ShowInfo();
Person incognito = new IncognitoPerson ();
incognito.ShowInfo();
Console.ReadLine();
}
}
public class Person
{
public virtual void ShowInfo()
{
Console.WriteLine("I am Person");
}
}
public class Teacher : Person
{
public override void ShowInfo()
{
Console.WriteLine("I am Teacher");
}
}
public class IncognitoPerson : Person
{
}
Upvotes: 1
Reputation: 5319
C# is different to java in the parent/child class override behavior. By default in Java all methods are virtual, so the behavior that you want is supported out of the box.
In C# you have to mark a method as virtual in the base class, then you will get what you want.
Upvotes: 2
Reputation: 647
You need to make it virtual
and then override that function in Teacher
. As you're inheriting and using the base pointer to refer to a derived class, you need to override it using virtual
. new
is for hiding the base
class method on a derived class reference and not a base
class reference.
Upvotes: 3