0

I'm using Visual Studio v12.0 and looking at the Settings.Designer.cs file in the Solution Explorer. In the Properties namespace, the Settings derived class is created from ApplicationSettingsBase class like so:

internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase

In the class, this line of code has me confused:

private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

This is an example of downcasting, I believe. I'm not clear why this is necessary. Why not just create an instance of Settings since it's already defined as inheriting the base?

Here's a longer snippet:

namespace ConfigMgrTest.Properties {

[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

    public static Settings Default {
        get {   
            return defaultInstance;
        }
    }

...rest of the namespace...

}

Tim Bostwick
  • 332
  • 3
  • 14

1 Answers1

1

the line:

Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

is equivalent to saying:

Settings s1 = new Settings();
SettingsBase synchronizedBaseSettings = global::System.Configuration.ApplicationSettingsBase.Synchronized(s1);
Settings settings = (Settings)synchronizedBaseSettings;

So the cast is required because ApplicationSettingsBase.Synchronized returns SettingsBase type. And ApplicationSettingsBase.Synchronized is called to make the settings object threadsafe. Otherwise you would have to: a) define defaultInstance as SettingsBase or b) do not call ApplicationSettingsBase.Synchronized and risk threading issues.

I guess nowadays the method ApplicationSettingsBase.Synchronized would be declared as a generic like this:

public static TSettings Synchronized<TSettings> (TSettings settingsBase) where TSettings: SettingsBase

But this class is probably older than generics in c# ;).

qbik
  • 5,502
  • 2
  • 27
  • 33
  • Many thanks, this nails it. BTW, if the casting notation used here a relic? I can only seem to find examples using the "as" keyword. – Tim Bostwick Jul 06 '14 at 18:21
  • @TimBostwick Not really, those operators (explicit cast and 'as') behave differently: http://stackoverflow.com/questions/132445/direct-casting-vs-as-operator – qbik Jul 07 '14 at 11:42