Welcome back! On Day 9 you learned how to catch your code's mistakes gracefully instead of letting them explode in your user's face. Today we tackle the Big One: classes and objects. This is where C# stops being "a scripting language with semicolons" and becomes a proper object-oriented powerhouse. Buckle up. ๐๏ธ
1. What Even Is a Class?
Remember our trusty analogy from Day 2 โ variables are labeled cardboard boxes? Well, a class is the blueprint for building a custom box. Not just any box โ a box that knows what it contains, what it can do, and how it should behave.
Think of it this way: a class is a cookie cutter. An object is the cookie. The cookie cutter defines the shape, but you can stamp out as many cookies as you want โ each one is its own independent cookie.
// The cookie cutter (class)
class Dog
{
public string Name;
public int Age;
}
// Stamping out cookies (objects)
Dog myDog = new Dog();
myDog.Name = "Biscuit";
myDog.Age = 3;
Dog yourDog = new Dog();
yourDog.Name = "Waffles";
yourDog.Age = 7;
myDog and yourDog are two separate objects, each with their own Name and Age. Change one, the other doesn't care.
2. Fields, Properties, and Why You Should Care
That Dog class above uses fields โ public variables slapped directly on the class. This works, but it's the C# equivalent of leaving your front door wide open. Anyone can reach in and change anything.
Properties are the polite way:
class Dog
{
public string Name { get; set; }
public int Age { get; set; }
}
Looks almost the same, right? But behind the scenes, { get; set; } creates a getter and setter โ little gatekeepers that control access. For now, they just pass values through. Later, you can add logic:
class Dog
{
public string Name { get; set; }
private int age;
public int Age
{
get => age;
set
{
if (value < 0)
throw new ArgumentException("Dogs can't have negative age!");
age = value;
}
}
}
Now nobody can set a dog's age to -5. The property protects the data. This concept is called encapsulation โ one of the four pillars of object-oriented programming (OOP). We'll meet the other three in later days.
3. Constructors - The Birth Certificate
When you write new Dog(), that () is calling a constructor โ a special method that runs when an object is born. If you don't write one, C# gives you a default empty one for free. But you can (and should) write your own:
class Dog
{
public string Name { get; set; }
public int Age { get; set; }
public Dog(string name, int age)
{
Name = name;
Age = age;
}
}
// Now you MUST provide name and age
Dog biscuit = new Dog("Biscuit", 3);
No more creating a nameless, ageless ghost dog. The constructor enforces that every Dog starts with valid data.
You can also have multiple constructors (this is called overloading):
class Dog
{
public string Name { get; set; }
public int Age { get; set; }
public Dog(string name, int age)
{
Name = name;
Age = age;
}
public Dog(string name) : this(name, 0)
{
// Puppy! Default age = 0
}
}
The : this(name, 0) part calls the other constructor โ no code duplication.
4. Methods - Teaching Your Objects Tricks
A class isn't just data โ it's data plus behavior. Methods are how objects do things:
class Dog
{
public string Name { get; set; }
public int Age { get; set; }
public Dog(string name, int age)
{
Name = name;
Age = age;
}
public string Bark()
{
return Age < 2 ? "Yip! Yip!" : "WOOF!";
}
public string Introduce()
{
return $"Hi, I'm {Name} and I'm {Age} years old. {Bark()}";
}
}
Dog biscuit = new Dog("Biscuit", 3);
Console.WriteLine(biscuit.Introduce());
// Hi, I'm Biscuit and I'm 3 years old. WOOF!
Notice how Introduce() calls Bark() โ methods can call other methods on the same object. The object is a self-contained little world.
5. Access Modifiers - The Velvet Rope
Not everything in a class should be public. C# has access modifiers to control who can see what:
publicโ anyone can access it. The front door.privateโ only code inside the same class can access it. The secret diary.protectedโ the class and its children can access it (more on inheritance later).internalโ anything in the same project/assembly can access it.
Rule of thumb: make everything private by default, then open it up only as needed. This is encapsulation in action.
class BankAccount
{
public string Owner { get; }
private decimal balance;
public BankAccount(string owner, decimal initialBalance)
{
Owner = owner;
balance = initialBalance;
}
public decimal GetBalance() => balance;
public void Deposit(decimal amount)
{
if (amount <= 0)
throw new ArgumentException("Deposit must be positive");
balance += amount;
}
public void Withdraw(decimal amount)
{
if (amount > balance)
throw new InvalidOperationException("Insufficient funds");
balance -= amount;
}
}
Notice balance is private. You can't do account.balance = 1000000; from outside โ you have to go through Deposit() and Withdraw(), which enforce the rules. That's the whole point.
6. static - The Singleton Weirdo
Sometimes you want something that belongs to the class itself, not to any particular object. That's static:
class Dog
{
public string Name { get; set; }
public static int TotalDogs { get; private set; } = 0;
public Dog(string name)
{
Name = name;
TotalDogs++;
}
}
Dog a = new Dog("Biscuit");
Dog b = new Dog("Waffles");
Console.WriteLine(Dog.TotalDogs); // 2
TotalDogs lives on the Dog class, not on any individual dog. You access it via Dog.TotalDogs, not a.TotalDogs.
You've already been using a static class without realizing it: Console. You never write Console c = new Console(); โ you just call Console.WriteLine() directly. That's because Console is a static class โ it can't be instantiated.
7. this Keyword and Object Identity
Inside a method, this refers to the current object:
class Dog
{
public string Name { get; set; }
public Dog(string name)
{
this.Name = name; // "this" is optional here but clarifies intent
}
public bool IsSameAs(Dog other)
{
return this == other; // Are they the exact same object in memory?
}
}
Dog a = new Dog("Biscuit");
Dog b = new Dog("Biscuit");
Dog c = a;
Console.WriteLine(a.IsSameAs(b)); // False โ same name, different objects
Console.WriteLine(a.IsSameAs(c)); // True โ c points to the same object as a
This is an important distinction: two objects can have identical data but be different objects. == on classes checks reference equality by default (are they the same thing in memory?), not whether they "look the same."
8. Your Homework: Build a Student Class
Create a Student class with:
- Properties:
Name(string),Grade(int, 0โ100) - A constructor that requires both
- A method
GetLetterGrade()that returns "A" (90+), "B" (80โ89), "C" (70โ79), "D" (60โ69), or "F" (below 60) - A method
Introduce()that returns something like: "I'm Alice, grade: 92 (A)"
class Student
{
public string Name { get; }
public int Grade { get; }
public Student(string name, int grade)
{
if (grade < 0 || grade > 100)
throw new ArgumentOutOfRangeException(nameof(grade));
Name = name;
Grade = grade;
}
public string GetLetterGrade()
{
return Grade switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F"
};
}
public string Introduce()
{
return $"I'm {Name}, grade: {Grade} ({GetLetterGrade()})";
}
}
Student alice = new Student("Alice", 92);
Console.WriteLine(alice.Introduce());
// I'm Alice, grade: 92 (A)
Bonus challenge: add a static method Student.GetClassAverage(Student[] students) that calculates the average grade across all students.
For the full reference, check out the C# classes tutorial on Microsoft Learn.
Summary of Day 10
- A class is a blueprint; an object is an instance of that blueprint.
- Properties (
{ get; set; }) protect data better than raw fields. - Constructors ensure objects start in a valid state.
- Methods give objects behavior โ data + behavior = objects.
- Access modifiers (
public,private,protected,internal) control who sees what. Default toprivate. staticmembers belong to the class itself, not to instances.Consoleis a static class you already know.- Reference equality: two objects with identical data are still different objects unless they're literally the same reference.
Tomorrow: we'll talk about Inheritance and Polymorphism โ the art of building new classes on top of existing ones. Your Dog class is about to have puppies... er, subclasses. ๐
See you on Day 11!