Constructors, static members
Build objects with constructors (including overloads and chaining) and use static fields/methods to hold data shared by all instances.
Constructors & static: overview
Goal: Construct objects safely and share data across instances.
- Constructors set required state
- Overloads & this(...) chaining
- Static fields/methods shared by all objects
Basic constructor
A constructor runs when you call new and initializes the object.
using System;
// Constructor sets required data on creation
public class User
{
public string Name { get; private set; }
public int Age { get; private set; }
public User(string name, int age)
{
Name = name;
Age = age;
}
}
public class Program
{
public static void Main(string[] args)
{
User u = new User("Ada", 28);
Console.WriteLine(u.Name + " (" + u.Age + ")");
}
}
All lessons in this course
- Fields, auto-properties, object initializers
- Constructors, static members
- Encapsulation & invariants