Search code examples
c#.netstack-overflow

StackOverFlow exception while setting a property via the construction


I have a simple class model with a single property inside.

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            UF uf = new UF(5);
        }
    }
}

namespace ConsoleApp1
{
    class UF
    {
        public UF(int N)
        {
            this.n = N;
            Console.WriteLine(this.n);
        }

        private int n
        {
            get => n;

            set
            {
                if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value));
                else
                {
                    n = value;
                }
            }
        }

    }
}

Who can explain to me why after class initialization via my constructor I am having the StackOverflow exception on the setter property?


Solution

  • Your exception comes from here :

    n = value;
    

    You have declared your property with the name of n and constantly tries to rewrite its value. Try renaming your property to something like N and it should be fine.

    class UF
    {
        public UF(int N)
        {
            this._n = N;
            Console.WriteLine(this.n);
        }
    
        int _n;
        private int N
        {
            get => _n;
    
            set
            {
                if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value));
                else
                {
                    _n = value;
                }
            }
        }
    
    }