जब भी कोई object create होता है, उसी समय उसकी initial setting करनी होती है।
यही काम C# में Constructor करता है।
Constructor वो खास method है जो object बनते ही अपने आप चलता है।
Constructor एक special method है:
इसका नाम class के नाम जैसा ही होता है
इसका कोई return type नहीं होता
Object बनते ही ये अपने आप run होता है
class Car
{
public Car()
{
Console.WriteLine("Car Object Created!");
}
}
Car c = new Car(); // Output: Car Object Created!
जैसे ही object बना → constructor अपने आप चल गया।
Constructor का उपयोग:
object की starting values set करने में
initial logic चलाने में
memory prepare करने में
default settings apply करने में
यानी object “जन्म लेते ही” तैयार हो जाता है।
जब आपका G17 / S15 GPS device server से जुड़ता है,
तो आप कुछ values पहले ही set करते हो:
IMEI
Connected Time
Battery
Status: Online
यही constructor से होता है।
class GPSDevice
{
public string IMEI;
public DateTime ConnectedTime;
public string Status;
public GPSDevice(string imei)
{
IMEI = imei;
ConnectedTime = DateTime.Now;
Status = "Online";
}
}
GPSDevice d = new GPSDevice("861128068064267");
जैसे ही device connect हुआ →
IMEI सेट → Time सेट → Status "Online" → सब अपने आप।
ये है constructor का असली use.
Admission लेते ही:
Roll No
Batch
Joining Date
Status = Active
Constructor ये सब set करता है।
class Student
{
public int RollNo;
public string Name;
public DateTime JoinDate;
public string Status;
public Student(int roll, string name)
{
RollNo = roll;
Name = name;
JoinDate = DateTime.Now;
Status = "Active";
}
}
जब भी user नया bill बनाता है:
Bill No generate
Date set
Total = 0
Customer assign
Constructor से bill तैयार।
class Bill
{
public int BillNo;
public DateTime Date;
public double Total;
public Bill(int billNo)
{
BillNo = billNo;
Date = DateTime.Now;
Total = 0;
}
}
Object बनाते समय data पास करने के लिए।
class Car
{
public string Model;
public Car(string model)
{
Model = model;
}
}
Car c = new Car("Swift");
जब constructor खाली हो।
class Test
{
public Test()
{
Console.WriteLine("Default Constructor");
}
}
Constructor object की पहली साँस है।
Object बनते ही सब कुछ तैयार कर देता है।
Real-life usage (C# में सबसे आम):
GPS device connect होते ही details set
Student admission में default values set
Billing software में new bill auto-create
Game Player spawn होते ही health set
Login पर user session initialize
0 Comments
Thanks for Commenting on our blogs, we will revert back with answer of your query.
EmojiThanks & Regards
Sonu Yadav