C# Object and Class

HTML
CSS
C#
SQL

Classes and Objects

Class

In object-oriented programming (OOP), a class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviours (methods) that objects of the class will have.

Object

An object is an instance of a class. It is a concrete entity that is created based on the blueprint defined by the class. Each object has its own unique set of data and can perform actions defined by the class’s methods.

Having the Main method in the same class

using System;

public class Car

{

    int year; // data member (also instance variable)

    string model; // data member (also instance variable)

    public static void Main(string[] args)

    {

        Car myCar = new Car(); // creating an object of Car

        myCar.year = 2022;

        myCar.model = “Toyota Camry”;

        Console.WriteLine(myCar.year);

        Console.WriteLine(myCar.model);

    }

}

Output: 2022 Toyota Camry

Having the main method in another class and creating two objects

using System;

public class Car

{

    public int year;

    public string model;

}

class TestCar

{

    public static void Main(string[] args)

    {

        Car toyota = new Car();

        toyota.year = 2022;

        toyota.model = “Toyota Camry”;

        Car ferrari = new Car();

        ferrari.year = 2008;

        ferrari.model = “Ferrari”;

        Console.Write(toyota.year + ” “);

        Console.WriteLine(toyota.model);

        Console.Write(ferrari.year + ” “);

        Console.WriteLine(ferrari.model);

    }

}

Output: 2022 Toyota Camry 2008 Ferrari

Practices Tasks

1. Define a Student class with properties for name, age, and grade. Implement an object to display the student’s details.

For example: define a class with the above-given properties and then use auto-implemented properties ({ get; set; }), which automatically generate a private field and getter/setter methods for accessing and modifying the property values. create an object and initialize the values to show the details in the console output like below.

2. Implement a BankAccount class with properties for accountNumber, accountHolder, and balance. Include methods for deposit, withdrawal, and displaying account information.

For example: define a class with the above-given properties then create the Deposit method allows depositing a specified amount into the account.It increments the Balance property by the amount provided. The Withdraw method allows withdrawing a specified amount from the account. check if the amount to withdraw is less than or equal to the current Balance.If sufficient funds are available (amount <= Balance), it deducts the amount from the Balance.If there are insufficient funds, it displays a message indicating “Insufficient funds!” to the console. then create a DisplayAccountInfo method to display the account information (AccountNumber, AccountHolder, Balance) to the console. Your output should like below