Lecture 7 Static Class Members
Lecture 7 Static Class Members
1
Outline
Static Field
Static Method
Static Property
Static Constructor
Static Class
Constant Field
2
Static Class Members
You can define class members as static using
the static keyword.
4
Example: Static Field
class Student
{
private string name;
private int age;
private static int numOfStudents; // Static Field
6
Example: Static Field
In this example, the static field numOfStudents
is incremented by the constructor every time a
new object is created.
10
Static Property
class Student {
public string Name { get; set; } // Property
public int Age { get; set; } // Property
private static int numOfStudents; // Static Field
public Student(string name, int age) {
Name = name;
Age = age;
numOfStudents++;
}
public static int NumOfStudents {
get {
return numOfStudents;
}
set {
numOfStudents = value;
}
}
11
}
Static Auto-Implemented Property
class Student
{
public string Name { get; set; } // Property
public int Age { get; set; } // Property
// Static Property
public static int NumOfStudents { get; set; }
12
Static Property
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Student.NumOfStudents);
Student.NumOfStudents = 5;
Console.WriteLine(Student.NumOfStudents);
Student s1 = new Student("Ali", 20);
Student s2 = new Student("Ahmed", 21);
Student s3 = new Student("Khaled", 22);
Console.WriteLine(Student.NumOfStudents);
}
}
13
Static Constructor
The static constructor is the special type that
does not take access modifiers or have
parameters.
It is called automatically before the first
instance is created or any static members are
referenced.
It is used to:
initialize any static data.
perform a particular action that needs to be
performed once only.
14
Example: Static Constructor
class Student {
public string Name { get; set; }
public int Age { get; set; }
public static int NumOfStudents { get; set; }
// Static Constructor
static Student() {
Console.WriteLine("Constructor will be called only once.");
NumOfStudents = 10;
}
}
15
Example: Static Constructor
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Student.NumOfStudents);
Student s1 = new Student("Ali", 20);
Student s2 = new Student("Ahmed", 21);
Student s3 = new Student("Khaled", 22);
Console.WriteLine(Student.NumOfStudents);
}
}
16
Static Class
A static class can contain only static members.
A static class cannot contain any instance data or
methods.
19
Constant Field
If a field is declared by using the keyword
const then it is a constant field.