Reputation: 7301
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."}
Upvotes: 0
Views: 341
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...
Upvotes: 1
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