C# Constructor - An Overview


Constructor is a special type of method which will have same name as that of the class. It is used to assign the values to variables during the Object Initialization and is Implicitly called during the Object Creation.

Contructor in C#


1. Special type of Method with same name as that of the Class.
2. It is Implicitely called during the Object Creation.
3. It is used to assign the values to the variable binded to the Object during the Object Creation.
4. Syntax

class A {
A() { }

A([parameters])
{ }
}

Types of Constructors


1. Default Constructor
A. Defined by the User or by the System.
B. No parameters
C. Class will have only one default constructor
Example

class A {
A() { } // Default Constructor

}

2. Parameterized Constructor
A. Defined by the User.
B. Takes Parameters
C. Class can have any number of parameterized constructors
Note: It will differ in Parameters datatype or Number of parameters.
Example:

class A {
A([parameters])
{
}
}

Methods verses Constructor


1. Methods
A. All methods will have different Names.
B. Takes Parameters and returns a value.
C. Explicitly invoked using the Objects.
2. Constructor
A. All Constructors will have same Name [Class Name].
B. Takes Parameters.
C. No Return Type
D. Implicitly Invoked.
Example
Define a class called Car with two variables brand, model and color. Define a Constructor to Assign the value and a Method to display the values.

// Example: Constructor in C#
class Car {
// variable declaration
String Brand;
String model;
double Price;

// Default Constructor(Without parameter)
public Car {
Brand = "Tata";
Model = "Nano";
Price=100000;
}

// Parameterized Constructor(With parameter)
public Car(String b, String m, double p){
Brand = b;
Model = m;
Price=p;
}
// Method to display the Car details
void showCarDetails() {
System.out.println("Brand = " + Brand);
System.out.println("Model = " + Model);
System.out.println("Price = " + Price);
}
} // End of the class definition

class CarDemo {
public static void main(String args[]) {
// Object Creation and Initialization
Car objCar1 = new Car(); // Invokes Default Constructor
objCar1.showCarDetails();

// Object Creation and Initialization
Car objCar2 = new Car("Maruthi", "Swift" 25000); // Invokes Parameterized Constructor
objCar2.showCarDetails();

}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: