Object-Oriented Programming (OOP) Part 1: Basics
8 min read
Welcome back, developer! ☕
If you have been writing code where you declare fifty variables at the top of your file like string userName1;, string userName2;, int userAge1;, and int userAge2;, you have likely felt the pain of "Spaghetti Code." It works, but it’s a nightmare to manage.
Today, we enter the realm of Object-Oriented Programming (OOP). This is not just a syntax change; it is a shift in mindset. Instead of writing a list of instructions for the computer to follow linearly, we will model our software based on real-world objects.
We are going to build a simple Role-Playing Game (RPG) system to demonstrate these concepts. ⚔️
1. Classes and Objects: Blueprints and Instances
The Definition
- Class: A user-defined data type that represents the structure (state) and behavior (methods) of a specific concept.
- Object: A concrete instance of a class existing in memory.
The Problem
Imagine you want to create a Hero for your game. Without OOP, you might do this:
string heroName = "Aragorn";
int heroHealth = 100;
int heroLevel = 1;
// What if we need a second hero?
string heroName2 = "Legolas"; // This gets messy fast.If you pass heroName to a function but forget heroHealth, your game logic breaks. There is no logical connection between these variables other than the similar names you gave them.
The Solution
We group these related variables into a single unit called a Class.
Think of a Class as the architectural blueprint for a house. You cannot live in the blueprint.
Think of an Object as the actual house built from that blueprint. You can build 50 houses (Objects) from one blueprint (Class).
Industry Practice
In C#, classes are usually defined in their own .cs files (e.g., Hero.cs).
// The Blueprint (Class)
public class Hero
{
// The data (State)
public string Name;
public int Level;
// The behavior (Method)
public void Announce()
{
Console.WriteLine("Here comes " + Name + "!");
}
}Now, let's build the objects in our Program.cs:
// Instantiation
// We use the 'new' keyword to allocate memory for this object.
Hero warrior = new Hero();
warrior.Name = "Aragorn";
warrior.Level = 10;
Hero archer = new Hero();
archer.Name = "Legolas";
archer.Level = 500; // Elves live long, right?
warrior.Announce(); // Output: Here comes Aragorn!
archer.Announce(); // Output: Here comes Legolas!🧠 Under the Hood: When you write
new Hero(), C# allocates memory on the Heap. The variablewarrioris actually just a reference (a pointer) on the Stack pointing to that memory address on the Heap.
2. Properties and Fields: Storing State
The Definition
- Field: A variable declared directly in a class or struct.
- Property: A member that provides a flexible mechanism to read, write, or compute the value of a private field.
The Problem
In the example above, we used public string Name;. This is a Field.
What happens if a junior developer joins your team and writes this?
warrior.Level = -50; // Levels can't be negative!
warrior.Name = null; // A hero with no name? Crash imminent.Public fields provide uncontrolled access. Anyone can set any value, potentially breaking your application state.
The Solution
We use Properties. Properties allow us to control how values are set (Validation) and retrieved.
Industry Practice
We rarely make fields public. The standard is to use Private Fields wrapped by Public Properties.
1. Full Property (When logic is needed)
Use this when you need to validate data before saving it.
public class Hero
{
// Private field (Backing field) - standard naming is _camelCase
private int _level;
// Public Property
public int Level
{
get { return _level; }
set
{
// Validation Logic!
if (value < 1)
{
_level = 1; // Default to 1 if they try to be funny
}
else
{
_level = value;
}
}
}
}2. Auto-Implemented Properties (Most Common)
If you don't need validation right now, use Auto-Properties. C# creates the private field for you automatically behind the scenes. It makes your code clean.
public class Hero
{
// C# creates a hidden private field for this automatically.
public string Name { get; set; }
// You can also restrict access
public int Id { get; private set; } // Can be read anywhere, but only set inside this class.
}🔥 Fun Fact: In early C#, writing properties required about 10 lines of code. Auto-properties
{ get; set; }were introduced to save developers from carpal tunnel syndrome.
3. Constructors: Initializing Your Objects
The Definition
- Constructor: A special method that is invoked automatically when an instance of a class is created.
The Problem
Right now, we can create a Hero like this:
Hero h = new Hero();
// h.Name is null right now.
// If we run h.Announce(), it prints "Here comes !" or crashes.An object should not exist in an invalid state. A Hero must have a name immediately upon birth.
The Solution
We use a Constructor to force the provider of the object to supply necessary data.
Industry Practice
Constructors have the same name as the Class and no return type.
public class Hero
{
public string Name { get; set; }
public string ClassType { get; set; }
// This is the Constructor
public Hero(string name, string classType)
{
// 'this' refers to the current instance we are building
this.Name = name;
this.ClassType = classType;
}
}Now, the compiler forces you to provide this data:
// Hero h = new Hero(); // ERROR: C# won't let you do this anymore!
// Correct usage:
Hero h = new Hero("Geralt", "Witcher");⚡ Pro Tip: If you do not define any constructor, C# provides an invisible "Default Constructor" (parameter-less) for free. The moment you define one constructor, C# removes the free one.
4. Access Modifiers: Public, Private, and Encapsulation
The Definition
- Access Modifiers: Keywords that define the visibility and accessibility of a class or its members.
The Problem
If every property and method in your Hero class is public, other parts of your program (like the InventorySystem or the EnemyAI) might accidentally change the Hero's health directly.
// In some other file...
hero.Health = 0; // Oops, I killed the hero by mistake.The Solution
Encapsulation. This is the concept of bundling data and methods that work on that data within one unit, and hiding the internal details.
The Modifiers
- Public: Access is not restricted. (The API/Interface).
- Private: Access is limited to the containing type. (The internal gears).
- Protected: Access is limited to the containing class and derived classes (Inheritance - we will cover this in Part 2).
- Internal: Access is limited to the current assembly (Project).
Industry Practice
The Golden Rule: Least Privilege. Make everything private by default. Only make things public if absolutely necessary.
public class Hero
{
// Private: Only the Hero class knows its exact health math.
private int _health;
public string Name { get; private set; } // Public read, Private write
public Hero(string name)
{
Name = name;
_health = 100; // Default start
}
// Public: The world can ask the hero to take damage
public void TakeDamage(int damage)
{
_health -= damage;
if(_health < 0) _health = 0;
PlayOuchSound(); // Calling a private helper method
}
// Private: The outside world doesn't need to know how sound works
private void PlayOuchSound()
{
Console.WriteLine("Oof!");
}
}By doing this, you ensure that no other coder can set _health to -500 directly. They must go through TakeDamage(), which contains your safety logic.
🧪 Putting it all together: The Code
Here is a complete, copy-pasteable example of industry-standard OOP basics.
using System;
namespace RpgGame
{
public class Hero
{
// 1. Auto-Properties for data that doesn't need complex logic
public string Name { get; } // Read-only property (can only be set in Constructor)
// 2. Private Field for data requiring validation
private int _level;
// 3. Public Property with validation logic
public int Level
{
get { return _level; }
set
{
if (value < 1)
Console.WriteLine("Level cannot be less than 1.");
else
_level = value;
}
}
// 4. Constructor: Setup the object
public Hero(string name, int startLevel)
{
Name = name;
Level = startLevel; // Goes through the 'set' logic above
Console.WriteLine($"{Name} has entered the world!");
}
// 5. Method: Behavior
public void Attack()
{
Console.WriteLine($"{Name} attacks with a sword! (Level {_level})");
}
}
class Program
{
static void Main(string[] args)
{
// Creating instances
Hero p1 = new Hero("Cloud", 1);
p1.Attack();
// Testing Encapsulation
p1.Level = -5; // Output: Level cannot be less than 1.
p1.Level = 2; // Valid
// p1.Name = "Sephiroth"; // Error: Property is read-only!
}
}
}📚 References & Further Reading
Challenge
Challenge: Implement the PlayerCharacter Class
Your task is to build a PlayerCharacter class for a fantasy RPG, strictly following the principles of encapsulation to ensure the character's data remains valid and secure.
Requirements:
Class Structure:
- Define a
publicclass namedPlayerCharacter.
- Define a
Fields & Properties:
- A
private static intfield to track the next available ID for a new character. Initialize it to1. Id: Apublic intproperty. It should be assigned a unique, auto-incrementing value upon creation and must not be changeable from outside the class.Name: Apublic stringauto-implemented property. It should be set only during construction.MaxHealth: Apublic intauto-implemented property. It should be set only during construction.Health: Apublic intproperty. This property requires custom logic:- It must be backed by a
private intfield. - The
getaccessor should return the value of the backing field. - The
setaccessor must ensure the new value is never less than0and never greater thanMaxHealth.
- It must be backed by a
IsAlive: Apublic boolread-only computed property. It should returntrueifHealthis greater than0, andfalseotherwise.
- A
Constructor:
- Create a single
publicconstructor that accepts astringfor the character's name and anintfor their maximum health. - Inside the constructor, assign the unique
Id, and initialize theName,MaxHealth, andHealthproperties. The character should start with full health.
- Create a single
Public Methods:
TakeDamage(int damageAmount): Apublicmethod that reduces the character'sHealth. The damage amount must be a positive number.Heal(int healAmount): Apublicmethod that increases the character'sHealth. The heal amount must be a positive number.
Expected result
A complete C# class definition for PlayerCharacter that adheres to all the specified requirements. The final code should demonstrate correct usage of:
privateandpublicaccess modifiers.- A
private staticfield for generating unique IDs. - Auto-implemented properties with
private setforId,Name, andMaxHealth. - A property (
Health) with a private backing field and custom validation logic in itssetaccessor. - A read-only computed property (
IsAlive). - A single constructor that correctly initializes the object's state.
- Public methods (
TakeDamage,Heal) that provide controlled access to modify the object's state.