0

Is there anyway for a static class to use values set in another static class from a different namespace to initialize some of it's members? Is there anyway to dictate the order they get established in?

e.g.

namespace Utility
{
    using Config;

    public static class Utility
    {
        public static UtilityObject myUtil = new UtilityObject(ConfigContext.myValue)
    }
}
...
// somewhere in a different file/project
...
namespace Config
{
    public static class ConfigContext
    {
        public static string myValue => ConfigurationManager.AppSettings["key"];
    }
}

This is a simplified example of the basic pattern I'm trying to accomplish; I would like to take values that are in a config file which are loaded into static class ConfigContext , and use them to initialize members of a static class Utility .

9
  • Move the using namespace_two statement outside of the namespace_one block and the code you have should work. Commented Jan 7, 2020 at 22:22
  • 2
    I don't know why you would want to do this but at least to me, it's a code smell. Looking to "dictate the order they get established in" suggests a temporal dependency. What does that even mean? Static class instances are created when you try to use them. Commented Jan 7, 2020 at 22:22
  • Yeah this is a hyper simplified example of what I'm trying to do but the core concept is the same. Basically I want to use values in a Config file that get loaded into a static ConfigContext to initialize members of a static Utility class. Commented Jan 7, 2020 at 22:24
  • 1
    Awesome. Thank you. I fail to see the problem. It looks like it should work although I wouldn't recommend this pattern. Not very unit-testable. Commented Jan 7, 2020 at 22:34
  • 1
    By the way, in case it's not obvious, I am not a big fan of static classes... :-P Commented Jan 7, 2020 at 22:39

1 Answer 1

1

You can't dictate the order of static initialization. But you can avoid the problem entirely by deferring initialization using lazy logic.

public static class Utility
{
    private static Lazy<UtilityObject> _myUtil = null;

    private static Utility()
    {
        _myUtil = new Lazy<UtilityObject>( () => new UtilityObject(ConfigContext.myValue) );
    }

    public static myUtil => _myUtil.Value;
}

Using this technique, the utility object isn't initialized until it is actually used.

If the logic to initialize ConfigContext has a similar issue, you can use a Lazy there too, and all of your lazy fields will get initialized in a cascading fashion, in the order they are needed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.