C# Static List: Global List Variable

Use a static List instance to store data in a unified location in a program.
Static List. A static List is effective for program-wide storage. It references a dynamic array of strings or other data types in only one location in your program.
List, notes. The static List can be put in a separate file in your program for ease of maintenance. Usually, separating classes into separate files is best.List
An example. This class allows you to store a variable number of elements in a single location. It is essentially a global variable that you can use from anywhere in your program.Static Constructor

Note: For many programs, this approach is fine. For more complex and large programs, more disciplined approaches are necessary.

Next: This code allocates the List in the static constructor. This is run before the List is needed.

Record: You can call the ListTest.Record method to add a string value to the list, and then call Display.

C# program that uses static List using System; using System.Collections.Generic; static class ListTest { static List<string> _list; // Static List instance static ListTest() { // // Allocate the list. // _list = new List<string>(); } public static void Record(string value) { // // Record this value in the list. // _list.Add(value); } public static void Display() { // // Write out the results. // foreach (var value in _list) { Console.WriteLine(value); } } }
Example 2. We add 3 strings to the static List instance in the class above. These strings can now be accessed from the static List instance above.

Also: We can display the strings using the special Display method on the ListTest type. We can use ListTest from any class.

C# program that uses class with List using System; class Program { static void Main() { // // Use the static List anywhere. // ListTest.Record("Dot"); ListTest.Record("Perls"); ListTest.Record("Net"); ListTest.Display(); } } Output Dot Perls Net
Using static instances. There are many ways you can use static instances of collections such as List. Consider a singleton—this is a design pattern surrounding a static instance.Singleton, Static Class
A summary. We used a static List. The term static refers to the single-instance state of the variable, meaning it belongs to the enclosing type and not the object instance.
For data collections that are not dynamic and do not expand, you can use a static array instead of a List. When multiple threads are used, static Lists can be problematic.Static Array
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to