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

Constructors

In this page:

  1. Constructors

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");
    }
}
🔒

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.