← Back to C# Course | Chapter 6: OOP Basics | Lesson 3 of 7

Constructors क्या हैं

एक constructor वह setup है जो किसी नए object के बनते ही अपने आप चलता है, जैसे किसी toy को box से निकलते ही assemble और charge करना। यह object को इसकी starting values देता है।

In this page:

  1. Constructors
Syntax
csharp
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

markup
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");
    }
}
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. #}
आम गलतियां
  1. constructor को एक return type देना, जो इसे एक साधारण method बना देता है।
  2. एक parameterized constructor define करना और फिर new Person() call करना, जो fail हो जाता है क्योंकि default वाला अब generate नहीं होता।
  3. ज़रूरत पड़ने पर this(...) या base(...) call न करना, fields को uninitialized छोड़ते हुए।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.