C# OOP: Classes & Objects
Object-Oriented Programming (OOP) organizes code around objects, which are instances of classes. A class is a blueprint that defines fields (data) and methods (behavior), and an object is a specific instance created from that class.
C# is a fully object-oriented language, and understanding classes and objects is essential for writing well-structured, real-world C# applications.
class ClassName {
// fields
// methods
}
ClassName obj = new ClassName();Defining a class
A class is defined with the `class` keyword, containing fields to store data and methods to define behavior. For example, a Car class might have fields for color and model.
Creating objects
An object is created from a class using the `new` keyword, like `Car myCar = new Car();`. Each object has its own copy of the class's fields.
using System;
class Car {
public string color = "Red";
}
class Program {
static void Main() {
Car myCar = new Car();
Console.WriteLine(myCar.color);
}
}RedmyCar is an object created from the Car class, and it has access to the color field.
using System;
class Car {
public string model = "Sedan";
public void Honk() {
Console.WriteLine("Beep!");
}
}
class Program {
static void Main() {
Car myCar = new Car();
myCar.Honk();
}
}Beep!Honk() is a method defined in the Car class, called on the myCar object.
Key points
- A class is a blueprint; an object is an instance of that class.
- Fields store data, and methods define behavior on a class.
- The `new` keyword creates a new object from a class.
- Multiple objects created from the same class have independent field values.
