I am a newbie in windows forms and I need to store a string that i can check through out my program, I have created the DataAccessClass.cs, Controller.cs, Entity.cs, I have a Form1.cs and many user controls. So basically One of the User Controls gets a string in a textbox but other classes in my program or other controls may need to check on the value of that string capture before. I would need to do things like
if([theStringThatMustBeAccessibleThoriugOut].Equals("Something"))
{
//do something
}
Again, i am a newbie and I would like an advise as to where to declare this variable, how to access it and how to store to it from any where and that it will be available anywhere. I know in asp.net i used to use Session["Blah"] and I would be able to get it at any point through out the life of the session. But in windows form i dont know how to do this..
Any help would be much appreciated.
You can always use a static variable of some class (which I’ll just call “Global”):
Which can then be accessed from anywhere as
Global.TheString.Be careful, though: static variables come with a cost. In particular, they can have negative effects on security and testability. For some reasons not to use static variables see the following:
http://hardcoded-dev.blogspot.com/2009/05/bad-habits-static-variables.html
http://gbracha.blogspot.com/2008/02/cutting-out-static.html
If you want to avoid some (but not all) of the problems associated with statics:
Note now that
TheStringis no longer static, andGlobal.Instancecan be changed at runtime. To access your special string, you can now useGlobal.Instance.TheString.