Classes and Objects
The Idea of OOP
In object-oriented programming (OOP) you model real-world things as objects. A class is the blueprint. An object is one actual thing built from it.
Simple example: A class
Car is the design drawing. Each real car, such as your red Toyota and my blue Honda, is an object made from that drawing. All cars have a color and can start, but each one has its own values.
Your First Class
csharp
class Dog
{
public string Name = ""; // field: data the object holds
public int Age;
public void Bark() // method: what the object can do
{
Console.WriteLine($"{Name} says Woof!");
}
}
Dog rex = new Dog(); // create an object
rex.Name = "Rex";
rex.Age = 3;
rex.Bark(); // Rex says Woof!
Dog luna = new() { Name = "Luna", Age = 1 }; // shorter forms
luna.Bark();
| Word | Meaning |
|---|---|
class | The blueprint |
new | Creates an object in memory |
| Field | A variable inside a class |
| Method | A function inside a class |
public | Everyone can use it |
Each Object Has Its Own Data
csharp
var a = new Dog { Name = "A" };
var b = new Dog { Name = "B" };
a.Age = 5;
Console.WriteLine(b.Age); // 0 : b is separate from a
Classes Are Reference Types
csharp
var first = new Dog { Name = "Rex" };
var second = first; // copies the REFERENCE, not the dog
second.Name = "Max";
Console.WriteLine(first.Name); // Max : both variables point to the same object
Common surprise: Assigning one class variable to another does not make a copy. Both names refer to the same object.
The this Keyword
csharp
class Counter
{
private int value;
public void SetValue(int value)
{
this.value = value; // this.value = the field, value = the parameter
}
}
static Members
A static member belongs to the class, not to a single object.
csharp
class MathHelper
{
public static double Pi = 3.14159;
public static int Double(int x) => x * 2;
}
Console.WriteLine(MathHelper.Double(5)); // 10, no object needed
Organize Files
- Put each class in its own file named after it:
Dog.cs - Use PascalCase for class names and public members
- Group related classes with a
namespace
csharp
amespace PetShop.Models; // file-scoped namespace
public class Dog
{
public string Name { get; set; } = "";
}
Conclusion
A class defines data and behavior, objects are the real instances and class variables hold references. Use static for things that belong to the class itself.
Quick Summary: class = blueprint, object = instance, new creates it, static belongs to the class.

