Static Members
Explore static members in C# to understand their distinction from instance members. Learn how static properties, methods, constructors, and classes operate without requiring object instantiation, and how to apply them effectively within object-oriented programming.
We'll cover the following...
We have used the static keyword regularly throughout this course, but we have not yet discussed what it means in detail.
Consider the following Person class:
class Person{public int Age { get; set; }public string Name { get; set; }}
Lines 3–4: We define two properties,
AgeandName, which are instance members by default.
To use this class, we must create an instance of it:
var person1 = new Person();person1.Age = 41;person1.Name = "John Doe";var person2 = new Person();person2.Age = 38;person2.Name = "Jim Terry";
Line 1: We create the first instance,
person1.Lines 2–3: We assign values to the
AgeandNameproperties ofperson1.Lines 5–7: We create a second instance,
person2, and assign it different values.
We now have two instances of the Person class. Each instance has its own copy of the Age and Name properties.