+ 3

Why in this code Ouptup is Second.Qu(object), not Second.Qu(int). Who knows?

Why in this code Ouptup is Second.Qu(object), not Second.Qu(int) ? https://code.sololearn.com/cwmo4kZyKVIQ/?ref=app

20th Dec 2018, 11:47 AM
Nelly Gevorgyan
Nelly Gevorgyan - avatar
2 Answers
+ 2
wow I did not know this, learned something today. quotte from first link : As I specified in the answers page: Derived.Foo(object) is printed - when choosing an overload, if there are any compatible methods declared in a derived class, all signatures declared in the base class are ignored - even if they're overridden in the same derived class! In other words, the compiler looks at methods which are freshly-declared in the most derived class (based on the compile-time type of the expression) and sees if any are applicable. If they are, it uses the "best" one available. If none is applicable, it tries the base class, and so on. An overridden method doesn't count as being declared in the derived class. end quote The overridden method counts as a method in the base class. So since 2 is also a object public void Qu(object a) is called. The compiler does not look at the most specific definition it looks at the first applicable one. Since public override void Qu(int a) is comming from the base class. The is the first to public void Qu(object a) pass the test. If you make it public void Qu(string a) then you will see "Second.Qu(int)" being printed. Because 2 is a int and an object but definite not a string https://stackoverflow.com/questions/2821620/different-behaviour-of-method-overloading-in-c-sharp https://social.msdn.microsoft.com/Forums/vstudio/en-US/a70b25d4-f310-4d06-9dc2-a453f822f4f3/function-not-getting-called-when-overloading-the-function-of-base-class-in-derived-class-with?forum=csharpgeneral https://stackoverflow.com/questions/27635376/can-we-overload-an-overridden-method Very cool thank you
20th Dec 2018, 10:12 PM
sneeze
sneeze - avatar
0
Sneeze THANKS A LOT :)
21st Dec 2018, 8:33 AM
Nelly Gevorgyan
Nelly Gevorgyan - avatar