views:

250

answers:

4

I'm trying to create a program with two (or more) discrete sets of settings, that both conform to the same interface. Particularly I'd like to do something like the following, using designer generated settings:

IMySettings settings = Properties.A;
Console.WriteLine(settings.Greeting);
settings = Properties.B;
Console.WriteLine(settings.Greeting);

This would be trivial with Go's interfaces because any class(?) that provides the methods can be assigned, but how can I implement this in C#, with its strict interface implementation rules?

Note: C#/.NET 2.0

+1  A: 

You can use interfaces in C#, too.

However, you'll have to write a facade class if you still want to use the designer-generated settings.

winSharp93
+1  A: 

I'm not sure if what you're asking is how to implement an interface in C#.

If it is, just make something like:

Public Interface IMySettings {
   Public string Greeting {get;set;}
}

Then just have your "A" and "B" implement this interface and returns your desired greeting. As a result your Properties class will implement IMySettings as opposed to a straight class:

Public class Properties {
   public IMySettings A {get;set;}
   public IMySettings B {get;set;}
}

So instead of using "MySettings", your code would look like so:

IMySettings settings = Properties.A;
MunkiPhD
If I understand correctly, this won't work because the settings class is auto-generated and does not implement an interface of this sort.
Steven Sudit
+2  A: 

The Properties.Settings class generated in VS is not going to let you do this. Consider defining a simple DTO class and marking it up with XmlAttribute so that you can easily deserialize it.

Steven Sudit
A: 

I'm not sure if you can do what you through the designer generated settings, but I don't use them often so I could be wrong. However, there is another way you could do this: creating your own ConfigurationSection.

Here is an example:

public class MyProperties : ConfigurationSection {
    [ConfigurationProperty("A")]
    public MySettings A
    {
        get { return (MySettings )this["A"]; }
        set { this["A"] = value; }
    }

    [ConfigurationProperty("B")]
    public MySettings B
    {
        get { return (MySettings )this["B"]; }
        set { this["B"] = value; }
    }
}

public class MySettings : ConfigurationElement {
    [ConfigurationProperty("greeting")]
    public string Greeting
    {
        get { return (string )this["greeting"]; }
        set { this["greeting"] = value; }
    }
}

And then your app.config/web.config needs the following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="mySettings" type="Namespace.MyProperties, Assembly"/>
    </configSections>
    <mySettings>
        <A greeting="Hello from A!" />
        <B greeting="Hello from B" />
    </mySettings>
</configuration>

There may be typos in that but the overall idea is there. Hope that helps.

akmad