Search code examples
c#loopsmethodsinfinite

C# Recursion Error - Extension Methods


I get an error here saying that the program could not exit the infinite loop.

public static class Program 
{
    public static void Main(string[] args)
    {
        Object obj = new Object();
        Console.WriteLine(obj.GetClassName());
    }

    public static string GetClassName(this object value)
    {
        return value.GetClassName();
    }  
}

Solution

  • you need to change your extension method to say:

    return obj.GetType().Name;
    

    your extension method is calling itself which is causing the infinite loop/recursion problem.