Stopbyte

How to fix a Stack Overflow Exception Error in My C# Program?

This is my program source code:

using System;
 
namespace MyConsoleApp
{
    public class PropertiesHolder
    {
        #region Fields
        
        private int value = 5;
        
        #endregion
        
        public int Value
        {
            get
            {
                return Value == 5 ? 1 : 0;
            }
            set
            {
                this.value = value;
            }
        }
    }
    
    public class MyProgram
    {
        public static void Main(string[] args)
        {
            PropertiesHolder ph = new PropertiesHolder();
            ph.Value = 10;
 
            Console.WriteLine(p.Value); // It crashes at this line.
            Console.WriteLine("Hello World!");
 
        }
    }
}

it crashes at the line number 33. i get a Stack overflow error, Why is that?

thanks

1 Like

avoid using that much confusing value, Value and this.Value members. use things like _value, _val…etc instead.

1 Like

I believe you’ve mixed up Value (global member) and value (local member). you need to edit your Value property:

public int Value
{
    get
    {
        return this.value == 5 ? 1 : 0;
    }
    set
    {
        this.value = value;
    }
}

that’s it.

1 Like

Thanks @afree @Jonathan Really good advice. That was the exact issue.