1

I have a static class where I want to have a SQLConnectionString be built.

public static class SharedUtilities
{
    public static SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();

    SharedUtilities()
    {
        connectionString.DataSource = "dx2v";
        connectionString.InitialCatalog = "Q619410";
        connectionString.UserID = "tunnelld";
        connectionString.Password = "david";
    }
}

This doesn't work, because you can have constructors on static classes. So how do I do it?

0

2 Answers 2

4

You forgot the static keyword on the constructor:

static SharedUtilities()

Because you omitted it, it defaulted to private, which is invalid for static classes.

See Static Constructors (MSDN).

1

One way to do it would be with a property that builds the object on demand (creating and filling out the private backing property).

public static class SharedUtilities
{
    private static SqlConnectionStringBuilder connectionString = null;

    public static SqlConnectionStringBuilder ConnectionString
    {
        get
        {
            if (connectionString == null)
            {
                connectionString = new SqlConnectionStringBuilder()
                {
                    DataSource = "dx2v",
                    InitialCatalog = "Q619410",
                    UserID = "tunnelld",
                    Password = "david",
                };
             }
             return connectionString;
         }
    }
}

For reference: Lazy Loading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.