Static Members
Understand the meaning of the static keyword.
We'll cover the following
Static vs. instance members
We’ve used the static
keyword regularly throughout this course, but haven’t really talked about what that means.
Consider the following class
:
class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
To use this class
, we have to create its instance:
var person1 = new Person();
person1.Age = 41;
person1.Name = "John Doe";
var person2 = new Person();
person2.Age = 38;
person2.Age = "Jim Terry";
We now have two instances of the Person
class
, and each instance has its own copy of the Age
and Name
properties.
In contrast to instance members that are bound to concrete instances of the class
, static
members are bound to the class
definition itself:
class Person
{
public static long Population { get; private set; } = 7000000000;
public int Age { get; set; }
public string Name { get; set; }
public Person()
{
Population += 1;
}
}
Because the Population
property isn’t bound to a concrete instance, it can be used as a shared variable between class
instances.
In terms of computer memory, static
members are located in the heap and are accessible by all instances of the class
where the static
member is defined.
Memory for a static
member is allocated when the program starts, even if no instance of this class
was created.
In our example, we increase the Population
by one whenever a new instance of the Person
class
is constructed.
Access static
members
Because we don’t need a class
instance to use static
members, we access them through the class
name:
Get hands-on with 1200+ tech skills courses.