The following class is declared as static and contains only static methods:
static class CompanyEmployee {
public static void DoSomething() { /*...*/ }
public static void DoSomethingElse() { /*...*/ }
}
A constant or type declaration is implicitly a static member.
A static member cannot be referenced through an instance. Instead, it is referenced through the type name. For example, consider the following class
While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.
It is not possible to use
this to reference static methods or property accessors.
If the static keyword is applied to a class, all the members of the class must be static.
Classes and static classes may have static constructors. Static constructors are called at some point between when the program starts and the class is instantiated.
public class Employee
{ public string id;
public string name;
public Employee4()
{ }
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
{ 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 and configure the employee object:
Employee e = new Employee (name, id);
Console.Write("Enter the current number of employees: "); string n = Console.ReadLine();
Employee.employeeCounter = Int32.Parse(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);
}
}
/*
Input:
sunil
SU643G
10
*
Sample Output:
Enter the employee's name: Matthias Berndt
Enter the employee's ID: SU643G
Enter the current number of employees: 10
Name: sunil
ID: SU643G
New Number of Employees: 11
*/