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


(Tas Dever) #1

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


(afree) #2

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


(Jonathan Jr) #3

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.


(Tas Dever) #4

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