Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Global Variables C#
Message
From
13/12/2009 05:21:08
 
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
C# 3.0
Miscellaneous
Thread ID:
01438724
Message ID:
01438819
Views:
62
Viv,

I seem to remember that the following construct does not call the initialization the first time an instance of a class is created
class AppSettings // no need to be static - but it can of course

       {
            public static string ConnString =  new SomeLongRunningProcess().GetConnString();

         }
http://msdn.microsoft.com/en-us/magazine/cc163857.aspx
Notice that ImplicitConstructor has an additional metadata flag named beforefieldinit. This flag allows the runtime to execute the type constructor method at any time it chooses, as long as the method executes before the first access to a static field for the type

http://msdn.microsoft.com/en-us/library/system.reflection.typeattributes.aspx
BeforeFieldInit Specifies that calling static methods of the type does not force the system to initialize the type.

If you have multiple static fields, I think that thay can be initialized the first time they are accessed, ie one can be initialized without the others being initialized

So instead of
static class AppSettings
>        {
>            public static string ConnString;
             public static string ConnString2;
>
>            static AppSettings()
>            {
>                ConnString = new SomeLongRunningProcess().GetConnString();
                 ConnString2 = new SomeLongOtherRunningProcess().GetConnString();

>            }
>        }
I would prefer
static class AppSettings
>        {
>            public static string ConnString =  new SomeLongRunningProcess().GetConnString();
             public static string ConnString2 =  new SomeLongOtherRunningProcess().GetConnString();

>        }
If there's a dependency between static fields, then it may be best to use a static constructor - just to make it clear

>Hi,
>
>The more subtle decision is probably whether to put these in a static or non-static class? In general I go for static because with something like this:
static class AppSettings
>        {
>            public static string ConnString;
>
>            static AppSettings()
>            {
>                ConnString = new SomeLongRunningProcess().GetConnString();
>            }
>        }
the long running bit is guaranteed not to be called unless the ConnString value is actually required elsewhere in code. If it were a non-static class the static constructor would fire un-neccessarily the first time an instance of the class was created....
>Best,
>Viv
Gregory
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform