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

Constructors

A constructor is the setup that runs automatically when a new object is created, like assembling and charging a toy as it comes out of the box. It gives the object its starting values.

In this page:

  1. Constructors
Syntax
csharp
class ClassName
{
    public ClassName(type parameter)
    {
        // initialize fields
    }
}

ClassName objectName = new ClassName(argument);

Constructors

A constructor is a special method that runs automatically when an object is created, typically used to initialize its fields. It shares the class's name and has no return type. If you don't define one, C# provides a default parameterless constructor.

Note: Use constructor parameters to force callers to provide required data at creation time.

Example: 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. #}
Common Mistakes
  1. Giving the constructor a return type, which makes it an ordinary method.
  2. Defining a parameterized constructor and then calling new Person(), which fails because the default one is no longer generated.
  3. Not calling this(...) or base(...) when needed, leaving 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.