0Pricing
C# Academy · Lesson

Defining Constructors

Create instances with parameterized constructors.

What Is a Constructor?

A constructor is a special method that runs when an object is created with new. It has the same name as the class and no return type. Its job is to put the object into a valid starting state.

using System;

class Dog
{
    public Dog()
    {
        Console.WriteLine("A dog was created");
    }
}

class Program
{
    static void Main()
    {
        var d = new Dog();
    }
}

Parameterized Constructors

A constructor can take parameters so the caller supplies initial values. This is the most common pattern for setting required data.

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()
    {
        var p = new Person("Ada", 36);
        Console.WriteLine(p.Name + " is " + p.Age);
    }
}

All lessons in this course

  1. Defining Constructors
  2. Constructor Chaining with this
  3. Object and Collection Initializers
  4. Static Constructors
← Back to C# Academy