Dear All,
I faced one interview question in polaris, They asked me to print the virtual method of the super class with the instance of B class. Is it possible by casting? if so please try and let me know.
class hirarical
{
public virtual void print()
{
Console.WriteLine("print virtual method");
}
public void printnorm()
{
Console.WriteLine("print virtual method");
}
}
class a : hirarical
{
public override void print()
{
Console.WriteLine("print a method");
//base.print();
}
}
class B : a
{
public override void print()
{
//need to access the virtual method of hierarical class with B instance can do casting with B instance
Console.WriteLine("print B method");
}
}
//need to access the
Loading

VulpesPosted Jan 8, 2015, 7:11 AM
but, unless it was something you really had to do, this would be bad programming IMO.
I can't think of any other way to do this using a cast or otherwise. In fact, I just did a quick google and came up with this thread where the Microsoft poster, Paul Zhou, appears to be agreeing with us on this:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/6a66b00d-e150-4852-abbd-2a37e7a9e4eb/how-to-call-a-virtual-method-of-an-ancestor-class-that-is-higher-than-the-base-class?forum=clr
Yadlapalli SrikanthPosted Jan 8, 2015, 6:54 AM
Thank you for the reply, I told the same to the interviewer, he was not agreed with me. Can
you please check any alternate solution is there.
VulpesPosted Jan 8, 2015, 6:02 AM
((hirarical)this).print();
because B's print() method would be called repeatedly.
Console.WriteLine("print a method");
The output is:
I'm not sure why there's also a non-virtual printnorm() method in the hirarical class which also writes 'print virtual method' to the console unless this is a trick question and you're suppose to call that instead. To do so then, of course, a cast works as it's non-virtual:
((hirarical)this).printnorm();