Question

I read When to Use Static Classes in C# but the top answer didn't necessarily answer my question. I've an application that interfaces with quite a bit of similar hardware, via an HTTP server. Each device must be logged into and the credentials are normally the same. I'm using Properties.Settings.Default.etc to handle application wide settings; however, for the ease I keep track of the last used username/password when individually logging into a device. The defaults that are settable through an options window are used first and remain the same unless changed via the options window, despite the temporary settings changing and being used in the defaults stead.

Anyway, that's the scenario...with regards to the question, I'm doing this:

private static class TemporarySettings
{
    public static string Username = Properties.Settings.Default["Username"].ToString();
    public static string Password = Properties.Settings.Default["Password"].ToString();
}

Is that stupid?

Was it helpful?

Solution

It's not stupid, and it may solve your problem perfectly (if it does, don't change it). There are some problems that this approach might cause down the road, though, and it helps to know what those are.

  1. If you want to change the user name and password without restarting your application, you won't have that option. You can write logic to watch the config file for change and reload the values if they change.
  2. If you want to "reuse" your code (especially if you put more behavior like monitoring for change) for multiple sets of username and password, you'll need to convert this to an instance.
  3. If you ever want to unit test classes that depend on this class, you will have a very difficult time stubbing the values.

To reiterate, though, you shouldn't shy away from the simplest solution (as you have defined) because of these potential issues unless you think there's a realistic chance that you'll be burned by them in the future. Otherwise, it will probably not be a very difficult refactoring to switch to an instance class later when the need arises.

OTHER TIPS

Even better, mark them readonly or use properties that only have a getters.

You are setting username and password to the same value, but other than that, no.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top