You can put
using MyNamespace;
at the top of all of the modules (and new namespaces) using the static list.
You will still need to reference it by its class name.
thines01
Postaholic
2,433 posts since Oct 2009
Reputation Points: 447
Solved Threads: 408
Skill Endorsements: 7
Variable (in your case a generic list) declared as public static is one solution to use it all over the project.
But if has its own weaknesses, like that it stays in memory for as long as your project is alive. And if the variable becomes huge, it can eat a lot of memory.
If you want to free the memory you should set the field to null so that the object the field has been pointing to becomes eligible for GC.
This only points out something: try to avoid static variables.
-------
What I would do to hold same referecne through all the classes of a project, is to pass the class reference to all the other classes, this way, you can access to non-static public field (or property).
Example:
class ClassForVarialbe
{
public List<string> stageManagementList;
public ClassForVariable()
{
stageManagementList = new List<string>();
}
//...
//you can even create a common method to do or check something
}
class Class1
{
void StartingMethod()
{
//here we`ll instantiate a new variable (generic list):
ClassForVariable cfv = new ClassForVariable();
//to access to the public variable and ADD into it, you can use the class referecne:
cfv.stageManagementList.Add("one");
//now open other class (and pass the referecne or a class where out variable is);
Class2 c2 = new Class2(cfv); //pass a class referecne
c2.AddToList(); //examle from class2 how to add into same list
//now open class3 and print data from list out:
Class3 c3 = new Class3();
c3.ReadFromList(cfv); //pass a class referecne to a method only
//NOTE: if you will do:
cfv = new ClassForVariable(); //you will loose all the data from the list!!!
}
}
class Class2
{
ClassForVariable cfv2; //accessible variable to all the class2
void MiddleMethod2(ClassForVariable _cfv2)
{
this.cfv2 = _cfv2;
}
public void AddToList()
{
cfv2.stageManagementList.Add("two");
}
}
class Class3
{
void MiddleMethod2()
{
//we could pass to constructor,
//but this example only passes to some of the methods bellow
}
public void ReadFromList(ClassForVariable _cfv3)
{
foreach(string item in cfv3.stageManagementList)
Console.WriteLine(item);
}
}
I hope you see what in the upper code is all about. The point is to keep the class alive (there the variable(s) is/are). As soon as you will use NEW keyword for a class, all data from class varaibles will be gone (reseted).
Mitja Bonca
Posting Maven
2,561 posts since May 2009
Reputation Points: 642
Solved Threads: 486
Skill Endorsements: 15
Question Answered as of 1 Year Ago by
Mitja Bonca
and
thines01