C sharp - class and object in C#

What is a Class in C#?

A class in C# is a blueprint or template for creating objects. It defines properties (data) and methods (behavior).Think of a class like a blueprint for a car. The class defines what a car has (wheels, color) and does (drive, brake).

What is an Object in C#?

An object is an instance of a class. It holds real data and can use the class's methods and properties.Using the blueprint (class), you can create many real cars (objects).

Syntax

 Class Definition

class ClassName
{
    // Fields or Properties
    // Methods
}

Creating an Object

ClassName obj = new ClassName();

Example: Class and Object in C#

using System;

class Car
{
    // Properties (fields)
    public string brand;
    public int year;

    // Method
    public void Start()
    {
        Console.WriteLine(brand + " is starting.");
    }
}

class Program
{
    static void Main()
    {
     Car myCar = new Car();
myCar.brand = "Toyota"; myCar.year = 2022; Console.WriteLine("Brand: " + myCar.brand); Console.WriteLine("Year: " + myCar.year); myCar.Start(); } }

Output:

Brand: Toyota
Year: 2022
Toyota is starting.

Components of a Class

Component Description
Fields / Properties Store data (e.g., string brand)
Methods Define behavior (e.g., Start())
Constructors Special methods to initialize objects
Access Modifiers Control access (e.g., public, private)