I'm fairly new to .Net... I have several queries which will execute when the application loads. I want these queries to store the data in an object (a dataset?) which is accessible throughout the application. Should I be using a singleton class? How can a User Control within my application reference public variables in the main application code?
I guess I haven't found a good resource on how / where to store application variables and how to reference them when I need to populate a ListBox, DataGridView, etc.
As a background I'm most familiar with developing using Flex Builder 3, sorry for the vague question... I'm having a problem locating a good reference on the topic (not just populating a Control, but storing the data at an application level and referencing it from anywhere within the app).
Edit: This is for programming a windows forms application using C#
In C# you cannot define true global variables (in the sense that they don't belong to any class). You can then retrieve the defined values anywhere in your code (provided it's part of the same namespace ): String code = Globals. CODE_PREFIX + value.
Declaring (Creating) Variablestype variableName = value; Where type is a C# type (such as int or string ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.
Global variables can be accessed from anywhere in a class or namespace. C# does not directly support global variables, but the functionality of global variables can be achieved by creating a static class, which is helpful in specific cases.
Application variable: it is used for entire application which common for all users. It is not for user specific. this variable value will lost when application restarted.
Sounds like you're using ASP.NET, in which case Application State (MSDN) will allow you to store and retrieve application-wide data that can be accessed from anywhere in the application.
More here:
How to: Save Values in Application State
How to: Read Values from Application State
If you're writing a desktop app, you should create a static class that contains your application wide data, e.g:
public static class ApplicationSettings
{
public static string InstallDirectory { get { ... } set { ... } };
public static DataSet SomeDataSet { get { ... } set { ... } };
static ApplicationSettings()
{
// ... initialize or load settings here
}
}
A singleton isn't necessary here, but if you do require lazy initialization and thread satefy you might want to take that route.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With