Lesson 18 of 34 · Classes & Objects
C# Classes and Objects
Until now you have worked with types that C# gives you: int, string, List<T>. The real power of C# comes from defining your own types. A class describes a kind of thing — a hero, a bank account, a spell — by bundling the data it has and the actions it can perform. This is the heart of object-oriented programming.
Defining a class
public class Hero
{
// fields: the data every hero has
public string Name = "";
public int Health = 100;
public int Level = 1;
// methods: what a hero can do
public void LevelUp()
{
Level++;
Health += 10;
}
public string Describe()
{
return $"{Name} (level {Level}, {Health} HP)";
}
}
A class is a blueprint. The variables declared inside it are called fields; each object gets its own copy. The methods have no static keyword: they are instance methods that work with the fields of one particular object.
Creating objects
new creates an object (an instance) from the blueprint:
Hero aria = new Hero();
aria.Name = "Aria";
aria.LevelUp();
Console.WriteLine(aria.Describe()); // Aria (level 2, 110 HP)
var bo = new Hero { Name = "Bo", Level = 5 }; // object initializer
Console.WriteLine(bo.Describe()); // Bo (level 5, 100 HP)
Each object has its own state: levelling up aria does not change bo. The object initializer syntax { Name = "Bo", Level = 5 } sets fields right after creation.
The this keyword
Inside an instance method, this refers to the current object. You rarely need it, except to tell a field apart from a parameter with the same name:
public class Counter
{
private int count;
public void Reset(int count)
{
this.count = count; // field = parameter
}
}
Classes are reference types
A variable of a class type holds a reference to an object, not the object itself. Copying the variable copies the reference:
Hero a = new Hero { Name = "Aria" };
Hero b = a; // the same hero, two names
b.Name = "Bran";
Console.WriteLine(a.Name); // Bran
A reference that points to no object is null. Calling a method on it throws a NullReferenceException — Chapter 6 shows how to guard against that.
Encapsulation: public and private
public members can be used by any code; private members only inside the class. Good classes keep their data consistent by controlling how it changes. Instead of letting everyone write hero.Health = -50, offer a method like TakeDamage that enforces the rules. In the next lesson you will meet properties, the idiomatic C# way to expose data safely.
Common mistakes
- Forgetting
new:Hero h; h.Name = "Aria";does not compile — the variable has no object yet. - Adding
staticto instance methods: astaticmethod cannot see the fields of an object. - Expecting
b = ato copy an object: both variables share one object.
Assignment
Complete the Hero class. The fields are already declared:
TakeDamage(amount)lowersHealthbyamount, but never below0.DrinkPotion()— if the hero has at least one potion, use one up and heal 25 HP, but never aboveMaxHealth. Without potions nothing happens.IsAlive()returnstruewhileHealthis above 0.Status()returns text like"Aria: 75/100 HP, 2 potion(s)".
Premium lesson
Unlock the full Learn C# course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Classes, objects and structs in other languages
- JavaScript Classes: Constructors, Getters and Setters · JavaScript
- Python Classes and Objects: __init__, Methods and Attributes · Python
- Go Structs: Define Your Own Types · Go
- Java Classes and Objects: Constructors and new · Java
Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.
Lesson last updated on .