I’m just curious about which among variables and methods inside a class were initialized first whenever a class is initialized. I have this code below to give you idea of what I am really troubled of:
public static class
{
private static int _revisionNumber;
private static Dictionary<string, bool> _jobBoardList;
private static readonly string ConnectionString = GetAppConfigData("JobBoardAutomationConnectionString");
private static readonly string ImportRunId = JobProcessingUtility.GetGuid();
private static readonly string TimeStampGuidString = CreateTimeStampGuidString(ImportRunId);
private static string _tempDirectoryForExportFiles;
........
private static string GetAppConfigData(string key)
{
return ConfigurationManager.AppSettings[key];
}
}
You can notice that i have a variable named “ConnectionString” and it is acquiring it’s value from the method named GetAppConfigData(string key), I’m just curious of which among methods and variables inside a class were created first whenever a class(not instances of the class) is initialized. Can someone please explain to me which was constructed first so that I could have a good idea of how to create classes and methods.
The variables are initialized in textual order (i.e. the order in source code), as per section 10.5.5 of the C# 4 specification:
So in your case, the initializer for
ConnectionStringwould be executed beforeJobProcessingUtility.GetGuid()is called.However, it’s generally not a good idea to rely on this, as it makes the code brittle – the simple act of reordering static variables could break the code. I’ve come across situations where it’s somewhat hard to avoid, but where possible you should avoid it.
Note that when there is still room for ambiguity with partial classes – the spec doesn’t make any guarantees there, although I’d expect all the static fields declared in one source file to be initialized, then all the ones in the other(s) to be initialized, with the order preserved within each source file. But no guarantees 🙂