Reputation: 5240
i have a class like this
public class Menu
{
public int MenuID { get; set; }
public string MenuName { get; set; }
public string LinkAddress { get; set; }
public Menu[] menu;
}
while i am trying to intilize in the constructor as follows i get an overflow exception error
public Menu() {
Menu[] menu = {
new Menu { MenuID = 1, MenuName = "Home", LinkAddress = "home/index" }
, new Menu { MenuID = 2, MenuName = "Gallery", LinkAddress = "Gallery/index" }
, new Menu { MenuID = 3, MenuName = "Academics", LinkAddress = "Academics/index" }
, new Menu { MenuID = 4, MenuName = "Blog", LinkAddress = "Blog/index" }
, new Menu { MenuID = 5, MenuName = "Login", LinkAddress = "Login/index" }
, new Menu { MenuID = 6, MenuName = "UserLogin", LinkAddress = "UserLogin/index" }
, new Menu { MenuID = 7, MenuName = "ForgotPassword", LinkAddress = "ForgotPassword/index" }
};
}
i also tried to intialize myvariable
public Menu[] menu;
in the constructor but i was not able to intialize it. can anyone tell me what exactly am i doing wrong. I thought constructor is used to intialize variables but i am not able to intiliaze it. thank you for your help.
Upvotes: 0
Views: 111
Reputation: 14389
you are made a circular reference when declaring an array of a class inside the class:
public Menu[] menu;//<-- declaring inside Menu class produces circular refernce
thus an overflow exception
Use a method instead, e.g:
public void InitMenu()
{
this.menu = new Menu[]{
new Menu { MenuID = 1, MenuName = "Home", LinkAddress = "home/index" }
, new Menu { MenuID = 2, MenuName = "Gallery", LinkAddress = "Gallery/index" }
, new Menu { MenuID = 3, MenuName = "Academics", LinkAddress = "Academics/index" }
, new Menu { MenuID = 4, MenuName = "Blog", LinkAddress = "Blog/index" }
, new Menu { MenuID = 5, MenuName = "Login", LinkAddress = "Login/index" }
, new Menu { MenuID = 6, MenuName = "UserLogin", LinkAddress = "UserLogin/index" }
, new Menu { MenuID = 7, MenuName = "ForgotPassword", LinkAddress = "ForgotPassword/index" }
};
}
and consume as:
Menu m = new Menu();
m.InitMenu();
m.menu=..;//<--acces your array
Upvotes: 1