Constructors क्या हैं
एक constructor वह setup है जो किसी नए object के बनते ही अपने आप चलता है, जैसे किसी toy को box से निकलते ही assemble और charge करना। यह object को इसकी starting values देता है।
In this page:
Syntax
class ClassName
{
public ClassName(type parameter)
{
// initialize fields
}
}
ClassName objectName = new ClassName(argument);
Constructors
एक constructor एक खास method है जो किसी object के बनते ही अपने आप चलता है, आमतौर पर इसके fields को initialize करने के लिए उपयोग होता है। यह class का नाम share करता है और इसका कोई return type नहीं है। अगर आप एक define नहीं करते, तो C# एक default parameterless constructor देता है।
Note:
callers को बनते समय ज़रूरी data देने के लिए मजबूर करने के लिए constructor parameters उपयोग करें।
उदाहरण: Constructors
using System;
class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person("Maya", 28);
Console.WriteLine($"{p.Name} is {p.Age} years old");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- constructor को एक return type देना, जो इसे एक साधारण method बना देता है।
- एक parameterized constructor define करना और फिर
new Person()call करना, जो fail हो जाता है क्योंकि default वाला अब generate नहीं होता। - ज़रूरत पड़ने पर
this(...)याbase(...)call न करना, fields को uninitialized छोड़ते हुए।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: