Can't reference a variable from App.config

416 views Asked by At

I'm trying to reference a variable from App.config in my C# file. Here's a sample of my code.

App.config:

<appSettings>
    <add key="ErrorEmails" value="[email protected]"/>
</appSettings> 

Code:

SettingsIO setIO = new SettingsIO();
public static string To = setIO.ReadSetting("ErrorEmails");

The error reads:

A field initializer cannot reference the non-static field, method, or preperty 'test.setIO'.

Should I be using a GET function? What am I doing wrong?

2

There are 2 answers

1
Dominic Scanlan On BEST ANSWER

Use the system.configuration class.

string str = System.Configuration.ConfigurationManager
                                 .AppSettings["someAppSetting"]
                                 .ToString();
0
n0rd On

From the error text I would guess that the lines you show are some class members declaration, i.e. code looks like this:

class MyAwesomeClass
{
    SettingsIO setIO = new SettingsIO();
    public static string To = setIO.ReadSetting("ErrorEmails");
}

Please notice, that To is a static member, while setIO is not.

The error message pretty clearly tells you that you cannot reference non-static member for member initialization. Static members are created at program start-up time, while non-static ones are only created when you create instance of your class, so there is no way to access non-static members when there is no instance of your class exists.

In order to make it work, you have to make both members static (It won't work if you make both non-static, but you can initialize them in class constructor instead in that case):

class MyAwesomeClass
{
    static SettingsIO setIO = new SettingsIO();
    public static string To = setIO.ReadSetting("ErrorEmails");
}

or

class MyAwesomeClass
{
    SettingsIO setIO;
    public string To {get; private set; } // don't make members public, use auto-properties instead

    public MyAwesomeClass
    {
        setIO = new SettingsIO();
        To = setIO.ReadSetting("ErrorEmails");
    }
}