🏗️ Constructors in C# (Implicit & Explicit)
A constructor is a special method used for initializing objects when they are created.
📌 What is a Constructor?
A constructor is called automatically when an object is created.
It has the same name as the class.
It does not have a return type.
It is used to initialize class variables.
If not defined, a default (implicit) constructor is provided by the system.
⚙️ Implicit Constructor (Default Constructor)
📌 Scenario
When no constructor is defined by the programmer, C# automatically provides one.
✅ Example
using System;
class Program
{
int a;
string b;
bool c;
// No constructor defined
static void Main()
{
Program p = new Program(); // Constructor is called
Console.WriteLine(p.a);
Console.WriteLine(p.b);
Console.WriteLine(p.c);
Console.ReadLine(); // Used to hold the screen
}
}
📤 Output
0
(null)
false
📌 Explanation
A class
Programis defined.Variables
a,b, andcare declared but not initialized.When the object is created:
int→ initialized to 0string→ initialized to nullbool→ initialized to false
This happens because of the implicit constructor provided by C#.
🛠️ Explicit Constructor
📌 Scenario
When a programmer defines a constructor manually to initialize values.
✅ Example
using System;
class Program
{
int a;
string b;
bool c;
// Explicit constructor
Program(int x, string y, bool z)
{
// 'this' keyword refers to current object instance
this.a = x;
this.b = y;
this.c = z;
}
static void Main()
{
Program p = new Program(10, "Chitransh", true); // Constructor is called
Console.WriteLine(p.a);
Console.WriteLine(p.b);
Console.WriteLine(p.c);
Console.ReadLine(); // Used to hold the screen
}
}
📤 Output
10
Chitransh
true
📌 Explanation
Constructor is explicitly defined with parameters.
Values are passed during object creation.
thiskeyword is used to refer to the current instance.Variables are initialized with user-defined values instead of defaults.
🧠 Key Takeaways
Constructors are essential for object initialization.
If not defined → implicit constructor is used.
Explicit constructors allow custom initialization.
thiskeyword helps differentiate between class variables and parameters.Constructors improve code clarity and control over object creation.
This concept is fundamental in Object-Oriented Programming (OOP) and frequently asked in .NET interviews.
Comments
Post a Comment