Ehsan Akbar
Ehsan Akbar

Reputation: 7301

Initialize a list of class in constructor returns overflow exception in c#

I have a simple class ,and i want to initialize it in the constructor as you can see here:

 public class CameraSetting
    {

        public  string CameraIP { set; get; }
        public  string CameraType { set; get; }
        public int CameraGroup { set; get; }
        public string GateId { set; get; }

        public List<CameraSetting> MyList { set; get; }
        public CameraSetting()
        {
            MyList = new List<CameraSetting>()
            {
                new CameraSetting() { CameraIP = "192", CameraGroup = 0, CameraType = "ورود",GateId = "1"},
                new CameraSetting() { CameraIP = "193", CameraGroup = 0, CameraType = "خروج",GateId = "1"},
                new CameraSetting() { CameraIP = "194", CameraGroup = 1, CameraType = "ورود",GateId = "2"},
                new CameraSetting() { CameraIP = "195", CameraGroup = 1, CameraType = "خروج",GateId = "2"}

            };
        }
    }

In my code i call CameraSetting obj=new CameraSetting();.but it returns this error :

{"Exception of type 'System.StackOverflowException' was thrown."}

enter image description here

Upvotes: 0

Views: 341

Answers (2)

Leo
Leo

Reputation: 14820

It's because each constructor creates four instances of the same type and the operation never ends. This is the order in which it happens...

  1. You create CameraSetting 1
  2. Then, CameraSettings instantiate 4 other CameraSettings
  3. Then, each of these CameraSettings create another 4 CameraSettings EACH! That is, 4 * 4 = 16
  4. Repeat indefinitely until the runtime kills the process with a StackOverflowException

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29016

Each time when you create an object of CameraSetting to add items to List, the constructor is invoked which forms a infinite loop here and that cause the exception.

I think it's better to take the List from the class and define it somewhere else as you needed. It is fine to use Like this in your main or some other places as required:

static void Main(string[] args)
{
    List<CameraSetting> _MyList = new List<CameraSetting>()
    {
        new CameraSetting() { CameraIP = "192", CameraGroup = 0, CameraType = "ورود",GateId = "1"},
        new CameraSetting() { CameraIP = "193", CameraGroup = 0, CameraType = "خروج",GateId = "1"},
        new CameraSetting() { CameraIP = "194", CameraGroup = 1, CameraType = "ورود",GateId = "2"},
        new CameraSetting() { CameraIP = "195", CameraGroup = 1, CameraType = "خروج",GateId = "2"}
    };
  // Rest of code here
}

Upvotes: 1

Related Questions