Classes & Objects
Learn the foundation of Object-Oriented Programming in C#: classes, objects, fields, and methods.
What is a Class?
A class is a blueprint that defines what data (fields) and behavior (methods) its objects will have. It doesn't take up memory on its own — it's a template.
What is an Object?
An object is a concrete instance of a class, created using the `new` keyword. Each object has its own independent copy of the class's fields.
class Car{ public string Model; public int Year;
public void Honk() { Console.WriteLine($"{Model} says beep beep!"); }}
var myCar = new Car { Model = "Civic", Year = 2022 };myCar.Honk();Click Run to see what this code prints.
Fields and Methods
Fields store an object's data; methods define what it can do. Together they model a real-world concept as code.
Creating Multiple Objects
var car1 = new Car { Model = "Civic", Year = 2022 };var car2 = new Car { Model = "Corolla", Year = 2023 };
Console.WriteLine(car1.Model); // CivicConsole.WriteLine(car2.Model); // Corolla — completely independentSince Car is a reference type, car1 and car2 are two separate objects on the heap, each with its own fields — changing one never affects the other.
FAQs
No — value types like `int` and `bool` are structs, not classes, though C#'s type system treats them consistently in most respects.
Summary
- A class is a blueprint; an object is an instance of that blueprint.
- Fields hold data, methods define behavior.
- Each object created with `new` has its own independent data.