DEV Community

ConnectSaravana
ConnectSaravana

Posted on

Basics - Class

  • What is a Class? A class is a data structure that may contain data members (constants and fields), function members (methods, properties, events, indexers, operators, instance constructors, finalizers, and static constructors), and nested types. Imagine you have different types of toys, like cars, dolls, and balls. Each toy is special and does different things. A class is like a group that keeps similar toys together.

For example, let's say we have a class called "Vehicle." Inside this class, we can put all the toy cars. The class "Vehicle" tells us that these toys have wheels, can move around, and make vroom-vroom sounds. It's like a special group for all the toy cars.

  • Why do we need a class? Having classes helps us organize and understand our toys better. It's like having different boxes for different types of toys. We can find our favorite toys easily because they are grouped together in a class.

So, a class is like a special group that helps us keep similar things together and understand them better.

``using System;

// Define the class
class Vehicle
{
    // Class properties
    public int NumberOfWheels;
    public string Sound;

    // Class constructor
    public Vehicle(int wheels, string sound)
    {
        NumberOfWheels = wheels;
        Sound = sound;
    }

    // Class method
    public void MakeSound()
    {
        Console.WriteLine(Sound);
    }
}

class Program
{
    static void Main()
    {
        // Create an object (toy car) from the Vehicle class
        Vehicle toyCar = new Vehicle(4, "Vroom-vroom!");

        // Access the object's properties
        Console.WriteLine("Number of wheels: " + toyCar.NumberOfWheels);

        // Call the object's method
        toyCar.MakeSound();
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)