PDA

Click to See Complete Forum and Search --> : [Resolved] [1.0/1.1] Static initialization


nebulom
Jul 17th, 2006, 10:16 PM
Is there any static block for C#, can't seem to find a bit.

private static IList categories = new ArrayList();
static
{
categories.Add("News and Features");
categories.Add("Kababayan Edition");
categories.Add("Hometown");
categories.Add("Owning a Home");
}

?

jmcilhinney
Jul 17th, 2006, 10:51 PM
Where does member initialisation get performed? In a constructor. Where does static member initialisation get performed? You guessed it. You should read this MSDN topic (http://msdn2.microsoft.com/en-us/library/ms229018.aspx) first.

nebulom
Jul 17th, 2006, 11:36 PM
Kewl. Thanks a bunch. I was just referring to java syntax and never tried to search. My bad. Again, thanks!

ComputerJy
Jul 18th, 2006, 02:14 AM
Where does member initialisation get performed? In a constructor. Where does static member initialisation get performed? You guessed it. You should read this MSDN topic (http://msdn2.microsoft.com/en-us/library/ms229018.aspx) first.
Actually this code isn't "Member Initialization". in Java Initializers run before constructors, only once.
They are used for static and non-static members

jmcilhinney
Jul 18th, 2006, 02:43 AM
My language was somewhat inaccurate. I should just said "initialisation" or "object initialisation". The first line of nebulom's code is initialisation of a member and it is executed before constructor code in C# also.

ComputerJy
Jul 18th, 2006, 02:49 AM
I'm not sure but I guess the first line doesn't have anything to do with the question.
I believe he was asking about static
{
categories.Add("News and Features");
categories.Add("Kababayan Edition");
categories.Add("Hometown");
categories.Add("Owning a Home");
}

jmcilhinney
Jul 18th, 2006, 03:17 AM
I realise that. I'm saying that the first line was initialising the member, i.e. assigning an initial value to the member variable, while the rest of the code would more correctly be termed "object initialisation", i.e. it is setting the new object being created to its initial state. I should have said in post #2 that "object initialisation" is done in a constructor. Initialisation of members can occur in a constructor or on the same line as their declarations, in which case it is executed before any constructors.