Creating instance or Creating object

Instance(also known as object) is a real world entities. We can access the fields and methods of the class using an object. So far, we created variables using datatypes like int, double, string etc. A class can also be used like a datatype. The variables declared using class is known as object or instance. We can create an instance of any class in C# using new keyword. To access the class members(fields and methods), we use the dot (.) operator after the object name. The dot operator links the name of an object with the name of a class member.

CODE

EG 1 . Creating Rectangle class with fields and variables and creating instance.

class Program {
    static void Main() {
        //Here wall is an object which is a real world entity
        Rectangle wall = new Rectangle();
        wall.length = 5;
        wall.width = 6;
        wall.height = 7;
        Console.WriteLine(wall.Area());
        Console.WriteLine(wall.Volume());
        Console.WriteLine(wall.Perimeter());
    }
}
//Creating class called Rectangle with its fields and methods.
class Rectangle {
    public double length, width, height;
    public double Area() {
        return length * width;
    }
    public double Perimeter() {
        return 2 * (length+width);
    }
    public double Volume() {
        return Area() * height;
    }
}



EG 2 . Creating Class called car with fields and variables

class Program {
    static void Main() {
        Car TataNexon = new Car();
        TataNexon.color = "Red";
        TataNexon.weight = 1315;
        TataNexon.numberOfSeats = 5;
        //Drive() is void method hence cannot be written inside Console.WriteLine()
        TataNexon.Drive();
        Console.WriteLine("Carrying Load Capcity = "+TataNexon.CarryingLoadCapacity()+"kg");
    }
}
class Car {
    public string color;
    public int weight, numberOfSeats;
    public void Drive() {
        Console.WriteLine("Start Driving");
    }
    public double CarryingLoadCapacity() {
        return (numberOfSeats*65)+30; //65 is the average weight of a person in kg, 30kg is for extra load for accessories,fuel etc.
    }
}




(Click Here, For more exercises)