Constructor in C#
Constructor is a class method which is called when an object of class is created.Constructor differs from other methods:
- Name of constructor is same as class name
- Constructor method could not return any value
This is the simplest constructor we can declare:
public class ElectronicDevice { public ElectronicDevice () { Console.WriteLine ("Creating ElectronicDevice"); } }
Now when we create an object of the class,the constructor is automatically called:
var obj=new ElectronicDevice();
If we execute that above code then “Creating ElectronicDevice” will be printed
If you want to pass different number and types of values then you can use:
- Constructor Overloading
- Assign Default value to constructor parameter
Constructor Overloading
Assign Default value to constructor parameter
Now if we modify our constructor as below,then we will have to pass an argument when creating an object of the class
public ElectronicDevice(int id) { Console.WriteLine("Creating ElectronicDevice"); }
now if we try to create an object of the class without passing an argument then we will get an error.This will throw error:
var obj = new ElectronicDevice();
To prevent this error from occuring we can assign default value to constructor parameter as:
public ElectronicDevice(int id=1) { Console.WriteLine("Creating ElectronicDevice"); }
Constructor of Base class
Below we have declared a base class.It defines one parameterless constructor:
public class ElectronicDevice { public ElectronicDevice () { Console.WriteLine ("Creating ElectronicDevice"); } }
This is the derived class.It also defines one parameterless constructor
public class Laptop : ElectronicDevice { public Laptop() { Console.WriteLine ("Creating Laptop"); } }
Now when we create an object of derived class,lets see which constructor is called.
using System; public class Program { public static void Main() { var obj=new Laptop(); Console.WriteLine("Hello World"); } }
The constructors are called in the following sequence if you execute the above code.
- ElectronicDevice
- Laptop
Though we have not explicitly called the constructor but it is automatically called when we create an object of the derived class.
If you have defined any parameterized constructors in the base class you need to call them from the derived class using the base keyword
public class Laptop : base(name) { }
Leave a Reply