C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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);
}
}
}
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