Can static variables be initialized in a method? Is the following code valid? Thank you!
internal static class Common
{
internal static int TimeOut;
internal static string Name;
internal static void Initialize()
{
TimeOut = Config.Read("timeout");
Name = Config.Read("Name");
}
}
Yes, they can. Your code is perfectly valid.
That being said, it’s often better to initialize then in a static constructor, or inline, as it prevents them from being used and accessed prior to initialization.
In your case, this would require using a static constructor, as you’re running code (
Config.Read):I would also recommend using Properties instead of Fields for your static values, as this does provide some benefits, especially in terms of future-proofing your API. This can be as simple as:
In your case, since these appear to be read once at initialization, you could potentially also use: