Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with fields, methods, properties, operators, and constructors, but cannot be used with indexers, destructors, or types.
public class MyBaseC { public struct MyStruct { public static int x = 100; } ...
To refer to the static member x
, use the fully qualified name (unless it is accessible from the same scope):
MyBaseC.MyStruct.x
Note The static keyword is more limited in use than in C++. To compare with the C++ keyword, see static in the C++ Language Reference.
To demonstrate instance members, consider a class that represents a company employee. Assume that the class contains a method to count employees and a field to store the number of employees. Both the method and the field do not belong to any instance employee. Instead they belong to the company class. Therefore, they should be declared as static members of the class.
For more information on constructors, see Instance Constructors in the Language Reference.
This example reads the name and ID of a new employee, increments the employee counter by one, and displays the information for the new employee as well as the new number of employees. For simplicity, this program reads the current number of employees from the keyboard. In a real application, this information should be read from a file.
// Static members using System; public class Employee { public string id; public string name; public Employee () {} public Employee (string name, string id) { this.name = name; this.id = id; } public static int employeeCounter; public static int AddEmployee() { return ++employeeCounter; } } class MainClass: Employee { public static void Main() { Console.Write("Enter the employee's name: "); string name = Console.ReadLine(); Console.Write("Enter the employee's ID: "); string id = Console.ReadLine(); // Create the employee object: Employee e = new Employee (name, id); Console.Write("Enter the current number of employees: "); string n = Console.ReadLine(); Employee.employeeCounter = Int32.FromString(n); Employee.AddEmployee(); // Display the new information: Console.WriteLine("Name: {0}", e.name); Console.WriteLine("ID: {0}", e.id); Console.WriteLine("New Number of Employees: {0}", Employee.employeeCounter); } }
Enter the employee's name: Tara Strahan Enter the employee's ID: AF643G Enter the current number of employees: 15 Name: Tara Strahan ID: AF643G New Number of Employees: 16