I am creating a project in Visual Studio 2010 using C#.
I have my main (program.cs) and several different classes in different file (class1.cs class2.cs class3.cs), and each class has its own function.
I was wondering if there is a way to set a variable (say in program.cs) that's accessible from each different class files?
To reduce confusion, I'll explain in example.
The program.cs is to create files. Each class is to create different type of files (txt, xml, xls, etc). I want to specify the path to save the file in program.cs, so if I want to change the path, I only have to change it in one place.
I want to set up a variable that's accessible from each class file, instead of passing the 'path' variable into the functions.
Is there a way to do so?
This kind of problem (a readonly value needed during execution of your app) could be solved adding a new settings through the setting property editor of your main project.
Now you can access this value from everywhere in your classes using
string path = Properties.Settings.Default.PathToExport;
Of course it is always possible to define, inside a class a static property and read this value, but writing a fixed path in the executable of a program is a very bad idea. If you want to change it you need to recompile and redistribute the application. Using the exe.config file you have a cleaner separation of code from configuration. (And changing the path to a shiny new server location requires to modify just the exe.config file)
You can do this using a public static property.
static class Program
{
public static string Path
{
get { return path; }
set { path = value; }
}
static string path = string.Empty;
}
So you can access the Path with Program.Path
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