We can overload the constructor if the number of parameters in a constructor
are different.
class Car {
Car() {
...
}
Car(string brand) {
...
}
Car(string brand, int price) {
...
}
Notice that,
Car() { } - has no parameter
Car(string brand) { } - has one parameter
Car(string brand, int price) { } - has two parameters
}
EXAMPLE OF CONSTRUCT OVERLOAD
using System;
namespace ConstructorOverload {
class Car {
// constructor with no parameter
Car() {
Console.WriteLine("Car constructor");
}
// constructor with one parameter
Car(string brand) {
Console.WriteLine("Car constructor with one parameter");
Console.WriteLine("Brand: " + brand);
}
static void Main(string[] args) {
// call with no parameter
Car car = new Car();
Console.WriteLine();
// call with one parameter
Car car2 = new Car("Bugatti");
Console.ReadLine();
}
}
}
Output
Car constructor
Car constructor with one parameter
Brand: Bugatti
cLASS AND OBJECTS
// C# program to illustrate the
// Initialization of an object
using System;
// Class Declaration
public class Dog {
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
// Property 1
public String GetName()
{
return name;
}
// Property 2
public String GetBreed()
{
return breed;
}
// Property 3
public int GetAge()
{
return age;
}
// Property 4
public String GetColor()
{
return color;
}
// Method 1
public String ToString()
{
return ("Hi my name is " + this.GetName()
+ ".\nMy breed, age and color are " + this.GetBreed()
+ ", " + this.GetAge() + ", " + this.GetColor());
}
// Main Method
public static void Main(String[] args)
{
// Creating object
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
Console.WriteLine(tuffy.ToString());
}
}
Output
Hi my name is tuffy.
My breed, age and color are papillon, 5, white
// C# Program to illustrate calling of
// parameterized constructor.
using System;
namespace ParameterizedConstructorExample {
class Geek {
// data members of the class.
String name;
int id;
// parameterized constructor would
// initialized data members with
// the values of passed arguments
// while object of that class created.
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
// Main Method
public static void Main()
{
// This will invoke parameterized
// constructor.
Geek geek1 = new Geek("GFG", 1);
Console.WriteLine("GeekName = " + geek1.name +
" and GeekId = " + geek1.id);
}
}
}