简体   繁体   中英

Is a static Application variable in c# a bad idea

I've two Classes

   public class DemoProperty 
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string MenuCode { get; set; }
        public string OriginalURL { get; set; }
     }

public class MyCommonProperties
{
        private static List<DemoProperty> _DemoList;
        public static List<DemoProperty> DemoList
        {
            get { return _DemoList; }
            set { _DemoList = value; }
        }
}

My need is to keep some common data throughout the project.For that I've using an application variable and it holds a Dictionary<string,List<DemoProperty>> .

Global.asx

void Application_Start(object sender, EventArgs e)
{
        Application["DemoProperty"] = new Dictionary<string,List<DemoProperty>>();
        MyCommonProperties.DemoList= (Dictionary<string,List<DemoProperty>>)Application["CommonProperties"];
}

Actually I don't know more about its demerits. If it is a bad idea could you please suggest me a good one.

What the static keyword ensures, is that the specific property / class exists only once in your application.

If this is bad or not is a very general question to which the answer unfortunately seems to be "it depends". Ultimately it is a question how you want to design you program.

Making something static can however make automatic testing harder, because you can not easily decouple your program into smaller testable parts (as all parts directly interact with your static data). It also makes reading the code harder, because it could be hard to understand when and what modifies the global data.

I will try an example to underline this:

class Data {
    public static string Entry;
}

class Operations {
    void SetOne() {
         Data.Entry = "one";
    }
}

With this example, for someone calling SetOne() it might be non-obvious that the method actually sets something in Data .

Another approach could be:

class Data {
    public string Entry;
}

class Operations {
    void SetOne(Data data) {
         data.Entry = "one";
    }
}

Now for the caller its is more obvious that Data is used in some way by the method, because the call now looks like SetOne(data) .

In my humble personal experience static was almost never a good idea. While it might make things quicker in the short run, its drawbacks concerning readability & testability of your code are usually too big to ignore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM