I would like to know/learn in more detail mechanism why this throw a stack overflow error ? (.Net Fiddle link)
(Related to the fact that DisplayType is present in both the Interface and the abstract class, renaming the later make it work. I would like to understand what is the execution path that lead to this overflow).
using System;
using System.IO;
public class Program
{
public static void Main()
{
Console.WriteLine("--------BEGIN--------");
FIVan van = new FIVan();
van.DisplayType();
Console.WriteLine("---------END---------");
}
}
public interface IVan
{
public Type TheType {get;}
public void DisplayType() => Console.WriteLine("Generic Type associated with this IVan<T> is : " TheType.ToString());
}
public abstract class AVan<T> : IVan
where T : class
{
public Type TheType { get => typeof(T);}
// NOTE : renaming DisplayType to something else (like Display()) doesn't Stack Overflow, it works.
public void DisplayType() => ((IVan)this).DisplayType();
}
public class FIVan : AVan<FileInfo>
{
}
EDIT : Actually I didn't fully realize how default interface implementation work. I add this edit to point you to this article I found interesting about it.
CodePudding user response:
AVan<T>.DisplayType()
overrides the default interface implementation specified by IVan.DisplayType()
. So it just calls itself recursively indefinitely.
If AVan<T>.DisplayType
is renamed, it calls into the default interface implementation instead, so does not cause a stack overflow.