is it possible to initialize a static class on app start up "automatically"? By automatically I mean without the need of referencing a property.
The reason I want to be able to do this for is that I'd like to automatically theme an app on start up.
Here's a short snippet:
static class Settings{
private static Theme _defaultTheme;
public static Theme DefaultTheme{
get{
return _defaultTheme;
}
private set{
_defaultTheme = value;
ThemeManager.SetTheme(value);
}
}
static Settings(){
DefaultTheme = Themes.SomeTheme;
}
}
I know I can ( and that's how it is at the moment ) go with original getter/setter and call
ThemeManager.SetTheme( Settings.DefaultTheme );
in constructor of App ( it's WPF project ) and it'll do the job, however, at least from my point of view ( correct me if I'm mistaken please ) it'd make more sense for the default theme to apply without the need of explicitly stating it.
is it possible to initialize a static class on app start up "automatically"? By automatically I mean without the need of referencing a property.
The only way to guarantee that the static constructor will execute is to use the type in some form. It does not necessary need to be referencing a property (it could be constructing an instance, using a method, etc), but you do need to use the type. It is possible for the static constructor to never run otherwise.
Your current option, or a variation of it, seems like the best solution. You could change this to having a single call such as:
Settings.InstallDefaultTheme();
If you prefer, since the reference of Settings
would force the static constructor to execute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With