Search code examples
c#oopstack-overflow

C# list/dictionary add method causes a StackOverflowException


When I try add values into List or Dictionary then I get

StackOverflowException error

stacktrace at Jaka_to_piosenka.MusicData..ctor ()

Here is my C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jaka_to_piosenka
{
    public class MusicData
    {
        public string Question { get; set; }
        public int GoodAnswerID { get; set; }
        public string SongFile { get; set; }

        List<MusicData> musicTable = new List<MusicData>
        {
            new MusicData { Question="a", GoodAnswerID = 3, SongFile="01.mp3" },
        };
    }
}

namespace Jaka_to_piosenka
{
    public class Game
    {
        public static void Main(string[] args)
        {
            var musicTbl = new MusicData();
        }
    }
}

What is the source of my problem?


Solution

  • Remove this section and find a better way of creating a list to get rid of the StackOverflowException

    List<MusicData> musicTable = new List<MusicData>
    {
          new MusicData { Question="a", GoodAnswerID = 3, SongFile="01.mp3" },
    };
    

    You can create a constructor that initializes the instance to some values but you cannot create a list of that same class within it.