Day 5: Classes, Objects & Properties
Welcome to Day 5! Today we dive into Object-Oriented Programming (OOP).
In C#, almost everything is an object. A class is simply the blueprint, and the object is the actual building created from that blueprint.
Creating a Class
Let’s model a basic User for a system. You create a class using the class keyword.
public class User
{
// Fields (Internal data storage)
private string _passwordHash;
// Constructors (How to build the object)
public User(string email)
{
Email = email; // Set the property using the passed-in value
}
// Properties (Public access points to data)
public string Email { get; set; }
// Methods (Behaviors)
public void SetPassword(string newPassword)
{
_passwordHash = "HASHED_" + newPassword;
}
}
Instantiating Objects
Now that we have the User class (the blueprint), let’s create actual User objects in our Program.cs. We use the new keyword to call the class constructor.
// Create a new instance of User
User myUser = new User("alice@example.com");
// Using properties and methods
Console.WriteLine(myUser.Email); // "alice@example.com"
myUser.SetPassword("superSecret123");
Deep Dive: Properties
In many languages (like Java), you have to write getEmail() and setEmail() methods manually to protect internal variables.
C# solves this elegantly with Properties.
Auto-Implemented Properties
If you don’t need custom logic, C# creates the hidden backing field for you automatically.
public int Age { get; set; }
Read-Only / Init-Only Properties
Often, you want someone to read a value, but not change it after the object is created.
// Only code inside the class can set the ID
public int Id { get; private set; }
// Using 'init' means it can only be set exactly during object creation
public string Username { get; init; }
Object Initialization Syntax
A beautiful shortcut for creating objects when setting multiple properties.
public class Product
{
public string Name { get; init; }
public decimal Price { get; set; }
}
// Creating an object without needing a massive constructor!
var laptop = new Product
{
Name = "MacBook Pro",
Price = 1999.99m
};
Challenge for Day 5
Create a Book class. Give it an init-only Title property, an Author property, and a Pages property. Create a list, or just manually instantiate three different Book objects using Object Initialization Syntax!
Tomorrow: Inheritance & Interfaces.