Search code examples
c#exceptionstack-overflowgetter-setter

Why does this code throw StackOverFlow Exception?


I was learning about getters and setters in C# and came across this code. I understand what's wrong here with the c# context. It has no compile-time errors but throws runtime exception. Can anybody explain what causes the call stack overflow?

using System;

class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        Console.WriteLine(test.Company);
    }
}

class Test
{
    public string Company
    {
        get
        {
            return Company;
        }
        set
        {
            Company = value;
        }
    }
}

Solution

  • That's because you call your property in your getter. You can do two things: add a field/member to you class:

    class Test
    {
        private string company;   
        public string Company
        {
            get
            {
                return company;
            }
            set
            {
                company = value;
            }
        }
    }
    

    Or change it to

    public string Company{get; set;}