Start learning free

LESSON 285 OF 674 · FUNCTIONS & CLASSES

Constructors in C#

Lesson

TL ; DR:

  • A constructor is a special method that runs automatically when you create an object with new. It's used to set up the object's initial state.


  • In C#, a constructor has the same name as the class and no return type:

    class Dog {
        public string name;
        public int age;
    
        public Dog(string name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    

  • Then create objects with arguments: new Dog("Rex", 4) — the constructor fills in the fields for you.



Full lesson:

In the previous lesson you set fields after creating the object:

Dog dog = new Dog();
dog.name = "Rex";
dog.age = 4;

That works, but it's noisy — three lines just to make one usable dog. And nothing forces you to set the fields, so it's easy to forget and end up with a half-baked object.

Constructors fix both problems. A constructor is a method that runs automatically the moment new Dog(...) is called. It takes the arguments you pass and uses them to initialize the new object's fields.


Defining a constructor

A C# constructor has two distinguishing features:

  • Its name is exactly the class name (Dog for a Dog class).

  • It has no return type — not even void.

class Dog {
    public string name;
    public int age;

    public Dog(string name, int age) {
        this.name = name;
        this.age = age;
    }
}

The this keyword

Notice this.name = name; in the body. The parameter name and the field name have the same identifier — without this, both sides would refer to the parameter (the local one wins inside a method).

this is a built-in reference to "the current object", so this.name means "the field on the object being constructed", and bare name is the parameter that was just passed in.


Calling the constructor

Once you've defined a constructor that takes arguments, every new call must provide them:

Dog rex  = new Dog("Rex", 4);
Dog luna = new Dog("Luna", 7);

By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna. No setup lines needed.


The default constructor

If you don't write any constructor, C# silently provides a hidden one that takes no arguments and does nothing — that's why new Dog() worked in earlier lessons. But the moment you define your own constructor, that freebie disappears: from now on you must call new Dog with the arguments you specified.


Your task

The Dog class already has the name and age fields declared. Add a constructor that takes a string name and an int age and assigns them to the matching fields using this. Then in MainFunction, create two dogs:

Dog rex  = new Dog("Rex", 4);
Dog luna = new Dog("Luna", 7);

Expected output:

Rex is 4
Luna is 7
STEP 1 OF 2
    Ctrl + Enter to check