pikausp
pikausp

Reputation: 1192

Initialize static class implicitly

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.

Upvotes: 5

Views: 1734

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564891

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.

Upvotes: 5

Related Questions