Chris
Chris

Reputation: 31206

Accessing Configuration Settings in a static context

It is possible to access the configuration settings value in a static context?

For instance, here is the code, which fails with a red line stating that one "cannot access non-static property 'Settings' in static context." All I need is the value of the setting.

namespace MyCompany.Sample.EmailConnector.Provider.Implementation
{
    class GmailEmailConnectorProvider : EmailConnectorProvider
    {
        private string clientSecret = Settings.ClientSecret; // Here is the error
                                         ^^

        public override Email SendTestEmail(string address, string message)
        {
            throw new NotImplementedException();
        }
    }
}

Upvotes: 0

Views: 532

Answers (2)

Rubens Farias
Rubens Farias

Reputation: 57936

You can also use the Default static property:

private string clientSecret = Settings.Default.ClientSecret;

Upvotes: 0

The Vermilion Wizard
The Vermilion Wizard

Reputation: 5395

You can't access properties of an object in field initializers like that. You need to move the initialization to a constructor

class GmailEmailConnectorProvider : EmailConnectorProvider
{
    private string clientSecret;

    public GmailEmailConnectorProvider()
    {
        clientSecret = Settings.ClientSecret;
    }
}

Also, it's generally not a good idea to do this (access the property from a constructor) if Settings is virtual, unless you seal GmailEmailConnectorProvider or you are otherwise certain that nothing will ever inherit from it.

Upvotes: 1

Related Questions