Why does this code results in Stack Overflow?

  • Thread starter Thread starter Abdu Rahman
  • Start date Start date
A

Abdu Rahman

Guest
The code below throws stack overflow. DoSomething in B calls DoSomething in A. DoSomething in A is supposed to call its X's implementation of method but it calls DoSomething of its derived class B. Why? is this a bug?

namespace Test
{
class Program
{
static void Main()
{
B b = new B();
b.DoSomething();
}
}
interface X
{
void DoSomething();
}
class A : X
{
protected void DoSomething() => ((X)this).DoSomething(); // Making visible to derived classes
void X.DoSomething() => Console.ReadKey();
}
interface Y : X
{
void DoSomethingElse();
}
class B : A, Y
{
public new void DoSomething() => base.DoSomething(); //Making publically visible
public void DoSomethingElse() { }
}
}


BTW this code works fine (if I do not inherit X in Y):

namespace Test
{
class Program
{
static void Main()
{
B b = new B();
b.DoSomething();
}
}
interface X
{
void DoSomething();
}
class A : X
{
protected void DoSomething() => ((X)this).DoSomething(); // Making visible to derived classes
void X.DoSomething() => Console.ReadKey();
}
interface Y
{
void DoSomethingElse();
}
class B : A, Y
{
public new void DoSomething() => base.DoSomething(); //Making publically visible
public void DoSomethingElse() { }
}
}









Allow time to reverse.

Continue reading...
 
Back
Top