C# Classes & Objects

What is a Class?

A class is a blueprint used to create objects.

It defines the structure of data (fields) and behavior (methods) that objects will have.

Loading...
Output:

Creating Objects

An object is an instance of a class. It is created using the new keyword.

Each object has its own copy of the class's data.

Loading...
Output:

Fields (Variables in Classes)

Fields are variables inside a class that store data for each object.

Each object gets its own version of these fields.

Loading...
Output:

Methods in Classes

Methods define behavior for objects.

They allow objects to perform actions using their data.

Loading...
Output:

Constructors

A constructor is a special method used to initialize objects when they are created.

It has the same name as the class and runs automatically when using new.

Loading...
Output:

The this Keyword

The this keyword refers to the current object.

It is commonly used to distinguish between class fields and constructor parameters.

Loading...
Output:

Multiple Objects

You can create multiple objects from the same class. Each object stores its own data.

Loading...
Output:

Why Use Classes?

Classes help organize code and model real-world concepts.

  • Group related data and behavior
  • Make code reusable
  • Improve readability
  • Support object-oriented programming

Practice

Create a Car class with brand and year. Then create two objects and print their details.

Loading...
Output:

Need Help?