Click here to Skip to main content
15,942,756 members
Please Sign up or sign in to vote.
3.08/5 (4 votes)
See more:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        private int _val;
        public int val
        {
            get
            {
                return val == 10 ? 1 : 0;
            }
            set
            {
                _val = value;
            }
        }


        public void Initialize(int value)
        {
            _val = value;

        }


    }
        class EntryPoint
        {

            static void Main(string[] args)
            {

                Program p = new Program();
                p.Initialize(10);
                Console.WriteLine(p.val);
                Console.ReadLine();

            }
        }

}
Posted
Updated 23-Jul-21 20:06pm
v3
Comments
ZurdoDev 24-Jun-13 12:01pm    
What's the question?

You're getting a stack overflow because of this section:

C#
public int val
{
get
{
return val == 10 ? 1 : 0;
}
set
{
_val = value;
}
}


Your get method is referencing the property name and not the private variable name. This means when you get the value of val, your code goes into a never ending loop as the result references itself. In .Net this will eventually cause a stack overflow exception.
 
Share this answer
 
Comments
[no name] 24-Jun-13 12:08pm    
Good catch
Rajesh Anuhya 24-Jun-13 12:26pm    
good +5
Thomas Daniels 24-Jun-13 12:41pm    
Good explanation, +5!
Sergey Alexandrovich Kryukov 24-Jun-13 12:55pm    
Problem solved, my 5.
—SA
Hi,

Try:
C#
public int val
{
    get
    {
        return _val == 10 ? 1 : 0;
    }
    set
    {
        _val = value;
    }
}

Just add an underscore before val == 10 ? 1 : 0;

Hope this helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900