In C# what does the term shadowing mean? I have read this link but didn't fully understand it.
Shadowing hides a method in a base class. Using the example in the question you linked:
class A
{
public int Foo(){ return 5;}
public virtual int Bar(){return 5;}
}
class B : A
{
public new int Foo() { return 1;}
public override int Bar() {return 1;}
}
Class B overrides the virtual method Bar. It hides (shadows) the non-virtual method Foo. Override uses the override keyword. Shadowing is done with the new keyword.
In the code above, if you didn't use the new keyword when defining the Foo method in class B, you would get this compiler warning:
'test.B.Foo()' hides inherited member 'test.A.Foo()'. Use the new keyword if hiding was intended.
Overriding : redefining an existing method on a base class
Shadowing : creating an entirely new method with the same signature as one in a base class
Suppose I have a base class that implements a virtual method:
public class A
{
public virtual void M() { Console.WriteLine("In A.M()."); }
}
I also have a derived class that also defines a method M:
public class B : A
{
// could be either "new" or "override", "new" is default
public void M() { Console.WriteLine("In B.M()."); }
}
Now, suppose I write a program like this:
A alpha = new B(); // it's really a B but I cast it to an A
alpha.M();
I have two different choices for how I want that to be implemented. The default behavior is to call A's version of M. (This is identical to the behavior if you applied the "new" keyword to B.M().)
This is called "shadowing" when we have a method with the same name but a different behavior when called from the base class.
Alternately, we could have specified "override" on B.M(). In this case, alpha.M() would have called B's version of M.
Shadowing consist on hiding a base class method with a new definition in a child class.
The difference between hiding and overriding has to do with the way methods are invoked.
That way, when a virtual method is overridden, the call address for the method call table of the base class is replaced with the address of the child routine.
On the other hand, when a method is hidden, a new address is added to the method call table of the child class.
When a call is made to the method in question:
The method call table class type is obtained, if we are invoking with a reference to the base class then the base class method table is obtained, if we have a reference to the child class, then the child class method table is obtained.
The method is searched in the table, if it's found then the invocation takes place, otherwise the base class method table is searched.
If we invoke the method with a reference to the child class then the behavior is the same, if the method has been overridden, the method address will be found in the base class, if the method was hidden the method address will be found on the child class, and since it has been already found, base class table will not be searched.
If we invoke the method with a reference to the base class then behavior changes. When overriding, as the method address overwrites base class entry, we will call the child method, even when holding a reference to the base class. With shadowing, the base class method table (which is the only one visible as we hold a reference to the base class) contains the virtual method address, and therefore, the base class method will be called.
In general shadowing is a bad idea, as it introduces a difference on the behavior of an instance depending on the reference we have to it.
Expanding on Kent's correct answer
When disambiguating when which method will be called, I like to think of shadowing vs. overriding with the following
Shadowing: The method called depends on the type of the reference at the point the call is made
Overriding: The method called depends on the type of the object at the point the call is made.
Here's an MSDN article on Shadowing. The language examples are in Visual Basic (unfortunately there is no equivalent C# page on MSDN), but it deals generally with the concepts and hopefully should help you understand anyway.
Edit: Seems like there is a C# article on shadowing, except that it's called hiding in C#. Also, this page offers a good overview.
If you want to hide Base class method , Use override in base [virtual method in base]
if you want to hide Child class method , Use new in base [nonvirtual method in base]->shadow
Base B=new Child()
B.VirtualMethod() -> Calls Child class method
B.NonVirtualMethod() -> Calls Base class method
Overriding: same name and exactly the same parameters, implemented
differently in sub classes.
If treated as DerivedClass or BaseClass, it used derived method.
Shadowing: same name and exactly the same parameters, implemented differently in sub classes.
If treated as DerivedClass, it used derived method.
if treated as BaseClass, it uses base method.
Hope this brief explanation helps.
Shadowing - Replaces the complete element of the parent class
class InventoryAndSales
{
public int InvoiceNumber { get; set; }
}
//if someone calls for this class then the InvoiceNumber type is now object
class NewInventoryAndSales : InventoryAndSales
{
public new object InvoiceNumber { get; set; }
}
Overriding - Only replaces the implementation. It doesn't replace the data type it doesn't replace like for example you have a variable it doesn't convert it into a method so if there is a method it will use that method and only changed the implementation
class InventoryAndSales
{
public virtual int GetTotalSales(int a, int b)
{
return a + b;
}
}
class NewInventoryAndSales : InventoryAndSales
{
//it replaces the implementation in parent class
public override int GetTotalSales(int a, int b)
{
return a * b;
}
}
Shadowing isn't something I'd be worried about understanding or implementing unless it "fits" the problem really well. I've seen it used improperly and cause weird logic bugs much more often than being used correctly. The big cause, I think, is when the programmer forgets to put overrides in a method signature then the compiler warning will suggest the new keyword. I've always felt that it should recommend using override instead.
private static int x = 10;
static void Main(string[] args)
{ int x = 20;
if (Program.x == 10)
{
Console.WriteLine(Program.x);
}
Console.WriteLine(x);}
Output:
10
20
I'm new to C# override and virtual. In the following example I want to call Callee method in B class from Caller method in A class. B inherits A. Any thoughts?
namespace Blah
{
public class Program
{
public static void Main(string[] args)
{
A a = new A();
a.Caller();
}
}
class A
{
public void Caller()
{
Console.WriteLine("In Caller");
Callee(); // How to make this call B:Callee() and make it print "in B"
}
public virtual void Callee()
{
Console.Write("In A");
}
}
class B : A
{
public override void Callee()
{
Console.Write("In B");
}
}
}
If you want to call the Callee method inside class B, you have first to create an instance of this class and then call this method:
var b = new B();
B.Callee();
If that is you are looking for (despite it does not make sense from a practical prespective), you should place the above two lines inside the method Caller in class A.
Usually we define a base class and if we think that a method in the class we define can be re-implemented from classes that would be derived from our class, we mark the method as virtual. When we derive a class from our base class and we do not override the virtual method, then the method that has been defined in the base class is called. Whereas when we have overriden a virtual method defined in a base class, the method in the derived class is called.
In your example you have the baseclass A with a subclass B that overrides a method in A. This means that you create an alternative A, that can interact as an A but might have different behavior.
However, this does not mean that every instance of A suddenly starts to use this definition. In your example you create a hard instance of A, but as the overriding method is in B it will never be called.
Instead you should create an instance of B, which you can cast to an A. Allowing your code to treat it as an A object, even though its B.
In your example, the only thing you'll need to do is create an instance of B (fiddle):
A a = new B();
a.Caller();
// Prints:
// In Caller
// In B
The way this works is more or less the same as Java inheritance, only in C# you need to mark methods as virtual in order to override them.
However, if your intention was to change definition of Callee in A without having to create a B (so new A().Caller()would print out "In B"), you should rethink whatever you are trying to do. It is something completely different from virtual methods and in most situations something you should try to avoid.
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?
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.
1. Abstract classes
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, Students and Teachers are Persons, 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 Students ShowInfo:
2. Virtual methods
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 Students:
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:
3. The magic `new` keyword aka "Shadowing"
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!
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.
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");
}
}
Virtual Methods
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.
Using New for Shadowing
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.
Early binding VS Late binding
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.
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.
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.
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.
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!
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.
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()
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
{
}
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.
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.
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");
}
}
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.
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();
}
}
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
Given the following code:
public class Base {
public virtual void Method() { }
}
public class Derived : Base {
public override void Method() { }
}
...
var baseMethodInfo = typeof(Base).GetMember("Method")[0];
var derivedMethodInfo = typeof(Derived).GetMember("Method")[0];
Is it possible to determine if the derivedMethodInfo represents a method declaration which overrides another in a base class?
In another question it was observed that had Method been declared abstract (and not implemented) in the base class, derivedMethodInfo.DeclaringType would have turned up as Base, which makes sense after reading #EricLippert's comments. I noticed that in the present example, since the derived class re-declares the method, that derivedMethodInfo.DeclaringType == derivedMethodInfo.ReflectedType, viz. Derived.
There doesn't seem to be any connection between baseMethodInfo and derivedMethodInfo, other than their names are the same and their respective declaring types appear in the same inheritance chain. Is there any better way to make the connection?
The reason I ask is that there appears to be no way to distinguish, through reflection, between the earlier example and the following one:
public class Base {
public virtual void Method() { }
}
public class Derived : Base {
public new void Method() { }
}
In this case as well, the Derived class both declares and reflects a member called Method.
A method shadowing a virtual method will have the VtableLayoutMask flag set in Attributes.
Note that an ordinary virtual method (with no similar name from a base type) will also have this flag set.
This flag appears to indicate that the method introduces a new entry in the VTable.
There's a more specific class MethodInfo which derives from MemberInfo. Note that not all kinds of members can be virtual (fields cannot, for example).
If you say
var derivedMethodInfo = typeof(Derived).GetMethod("Method");
then you can check if
derivedMethodInfo.GetBaseDefinition() == derivedMethodInfo
or not. See documentation for GetBaseDefinition() where they also have a code example.
Below code:
public class Program
{
static void Main(string[] args)
{
father f = new son(); Console.WriteLine(f.GetType());
f.show();
}
}
public class father
{
virtual public void show()
{
Console.WriteLine("father");
}
}
public class son : father
{
public override void show()
{
Console.WriteLine("son");
}
}
The result is 'son'.
If I modify the 'public override void show()' to 'public new void show()',the result is 'father'.
So I conclude below 'rules':
Use 'override', which function will be called is determined in run
time. The program will choose the right function according to the
real type of current object.(As above, the f's runtime type is son,
so it calls the son's show.)
Use 'new' modifier, which function will be called is determined when
it is compiled.The program will choose the object's declared type to
call its function.(As above, the f's declared type is father ,so
using 'new' modifier make the output to show 'father'.
All above are what I understand about polymorphism.Any misunderstanding and wrong?
Use 'new' modifier, which function will be called is determined when it is compiled.The program will choose the object's declared type to call its function.(As above, the f's declared type is father ,so using 'new' modifier make the output to show 'father'.
Not really. The decision is still made at execution time, but the new method does not override the virtual method in the base class. This is most easily shown by extending your example somewhat:
using System;
class Base
{
public virtual void Foo()
{
Console.WriteLine("Base.Foo");
}
}
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("Derived.Foo");
}
}
class MoreDerived : Derived
{
public new void Foo()
{
Console.WriteLine("MoreDerived.Foo");
}
}
class Test
{
static void Main()
{
Base x = new MoreDerived();
x.Foo(); // Prints Derived.Foo
}
}
Here, at compile time the decision is made to call the most overridden implementation of Base.Foo - if there were multiple Foo signatures, the decision about which signature to use would be taken, for example. Which implementation will be "the most overridden" is unknown at this point, of course.
At execution time, the CLR will find that most overridden implementation based on the actual type of the target object - which is MoreDerived. But MoreDerived.Foo doesn't override Base.Foo... whereas Derived.Foo does, so the implementation in Derived is the one which is actually executed.
Use 'new' modifier, which function will be called is determined when it is compiled.The program will choose the object's declared type to call its function.(As above, the f's declared type is father ,so using 'new' modifier make the output to show 'father'.
This is slightly wrong. Using new means that this function does not override any functions of the base class. The function dispatch still happens at runtime, but this function is not considered. The difference would be clearer if you had Grandson or Daughter classes to test more.
yes it work like that only...your understanding is right..
But for second case when you use new intad of override it hide actual implementation i.e. parent class implementation
As the new keyword was used to define this method, the derived class method is not called—the base class method is called instead.
EXample from MSDN
// Define the base class
class Car
{
public virtual void DescribeCar()
{
System.Console.WriteLine("Four wheels and an engine.");
}
}
// Define the derived classes
class ConvertibleCar : Car
{
public new virtual void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("A roof that opens up.");
}
}
class Minivan : Car
{
public override void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("Carries seven people.");
}
}
call to the class
Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
output
Car object: YourApplication.Car
Four wheels and an engine.
----------
Car object: YourApplication.ConvertibleCar
Four wheels and an engine.
----------
Car object: YourApplication.Minivan
Four wheels and an engine.
Carries seven people.
----------
MSDN having good example of it : Knowing When to Use Override and New Keywords (C# Programming Guide)
A normal method is called by type of class and a virtual method is called by content of memory allocated to the object. Now keyword new hides the concept of polymorphic and just care for its type.