C# Object Oriented Programming( Classes & Objects)

C# Object Oriented Programming( Classes & Objects)

Classes & Objects

An object is something material that you can touch or feel (Car, Laptop, Cell Phone...etc). When a car is being manufactured, engineers don't come up with a new design for every single car they built. instead, they use a single design to build thousands of cars. In OOP we create a class(design) to build many objects(cars). A class is a template for building objects. Let's take a closer look.

First, let's create a vehicle class by using a class keyword

class Vehicle {
string Name = "BMW";
string Model = "M8";
string BodyType = "Coupe";
string Colour = "Black";

}

Now to call the vehicle class and create a new instance of it as an object, we use the new keyword and the name of the class with brackets to show that this is an object

class Vehicle {
string Model = "M8";
string BodyType = "Coupe";
string Colour = "Black";

}
Vehicle Car = new Vehicle();
Console.WriteLine($"Vehicle 1  name:{Car.name} Model:{Car.Model} BodyType: {Car.BodyType} Colour:{Car.Colour}")

Output

Vehicle 1 name: BMW Model: M8 BodyType: Coupe Colour :Black

Let's create a second car and make it white

class Vehicle {
string Model = "M8";
string BodyType = "Coupe";
string Colour = "Black";

}
Vehicle Car = new Vehicle();
Console.WriteLine($"Vehicle 1  name:{Car.name} Model:{Car.Model} BodyType: {Car.BodyType} Colour:{Car.Colour}");

Vehicle Car2 = new Vehicle();
Car2.Colour = "White";

Console.WriteLine($"Vehicle 2  name:{Car2.name} Model:{Car2.Model} BodyType: {Car2.BodyType} Colour:{Car2.Colour}");

Output

Vehicle 1 name: BMW Model: M8 BodyType: Coupe Colour :Black
Vehicle 2 name: BMW Model: M8 BodyType: Coupe Colour :White

Conclusion

The reason why we use classes and objects is so that we don't repeat unnecessary code. it's a way to extract out the codes that are common for the application, place them in a single place, and reuse them instead of repeating them.