0

I wrote code below where I use the Id to fill in the name.

namespace ConsoleApp1
{
    class test
    {
        public int Id { get; set; }
        public string Name { get { return Name; } set { Name = Id.ToString(); } }
    }
    class Program
    {
        static void Main(string[] args)
        {

            List<test> t1 = new List<test>();

            t1.Add(new test() { Id = 1 });
            t1.Add(new test() { Id = 2 });
            t1.Add(new test() { Id = 3 });
            t1.Add(new test() { Id = 4 });
            t1.Add(new test() { Id = 5 });

            Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(t1));
        }
    }
}

When the code runs, an exception is raised:

Exception of type 'System.StackOverflowException' was thrown`.

How resolve problem?

0

1 Answer 1

2

When you call the Name get property, your code says "get the name by calling the Name get property" and the system gets stuck in an infinite loop. Similarly, your set property is telling the system to call the set property again.

Change

public string Name { get { return Name; } set { Name = Id.ToString(); } 

to

public string Name { get { return Id.ToString(); } } 
1
  • 2
    A shorter version is public string Name => $"{Id}"; Commented May 8, 2021 at 8:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.