Classes and Objects in C#
Defining classes, constructors, and creating instances — the foundation of object-oriented C#.
2 min read
A class is a blueprint; an object (or instance) is a concrete thing built from that blueprint. C# is built around this distinction from the ground up.
Defining a class
class User
{
public string Name;
public int Age;
public void Greet()
{
Console.WriteLine($"Hi, I'm {Name}");
}
}Name and Age are fields — data the object holds. Greet is a method — behavior the object can perform. Create an instance with new:
var user = new User();
user.Name = "Ada";
user.Age = 30;
user.Greet(); // "Hi, I'm Ada"Constructors
Setting fields one at a time after construction is error-prone — nothing stops you from forgetting one. A constructor lets you require the data up front:
class User
{
public string Name;
public int Age;
public User(string name, int age)
{
Name = name;
Age = age;
}
public void Greet()
{
Console.WriteLine($"Hi, I'm {Name}");
}
}
var user = new User("Ada", 30);Once a class has a constructor with parameters, the parameterless new User() is no longer available unless you define it explicitly too — which is usually exactly what you want: it forces every User to be created with the data it actually needs.
Primary constructors
C# 12 introduced a shorter syntax for the common case of "constructor just assigns parameters to fields":
class User(string name, int age)
{
public void Greet()
{
Console.WriteLine($"Hi, I'm {name}");
}
}The constructor parameters (name, age) are available throughout the class body without a separate field declaration or assignment. This trims a lot of boilerplate for simple classes, though for public properties you'd combine it with the property syntax covered next.
Instance vs. static members
Everything so far has been an instance member — it belongs to a specific object. static members belong to the class itself, shared across every instance:
class Counter
{
public static int TotalCreated = 0;
public Counter()
{
TotalCreated++;
}
}
var a = new Counter();
var b = new Counter();
Console.WriteLine(Counter.TotalCreated); // 2Notice TotalCreated is accessed through the class name (Counter.TotalCreated), not an instance — that's the tell that something is static. Use static members sparingly, for things that are genuinely shared across all instances, like a running count or a shared configuration value.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.