Lesson #26 - C# Constructors

A constructor is a type of method that we can add to a class to initialize the class object. The use of constructors is highly recommended as it is called when an object of a class is created. By default, each class has its constructor created default by C#. However, this constructor will not allow setting initial values as you can do while creating it yourself.


Let's see how can we create a constructor and use it when creating the class object


class Vehicle

{

//Create a class constructor (without Parameters)

public Vehicle()

{

}

}


class Program

{

static void Main(string[] args)

{

//Creating an object using ctr without Parameters

Vehicle ctr1 = new Vehicle();

}

}


Constructor Parameters

Constructors can also take parameters, which are used to initialize the object files.


class Vehicle

{

//Create a class constructor with all Parameters_1

public Vehicle(string vehicletype, int vehicleid, string vehiclecolor, bool sellstatus, int price, int weight)

{

string VehicleType = vehicletype;

int VehicleID = vehicleid;

string VehicleColor = vehiclecolor;

bool IsReadyForSell = sellstatus;

int Price = price;

int Weight = weight;

}


//Create a class constructor with partial Parameters_2 (With default values)

public Vehicle(string vehicletype, int vehicleid, string vehiclecolor) :this (vehicletype, vehicleid, vehiclecolor,true,1,2)

{

}

}



class Program

{

static void Main(string[] args)

{

//Creating an object using ctr and passing parameters

Vehicle ctr1 = new Vehicle("Car", 123412, "Red", true,32,13);


//Creating an object using ctr and passing only partial parameters using Parameters_2 ctr

Vehicle ctr2 = new Vehicle("Car", 123412, "Red");

}

}




1 view0 comments