Loading...

C# Constructors

Write a class Box with an int field size and a constructor Box(int n) that sets size = n;. In Pine, keep Main and build one box with Box b = new Box(4);, then write b.size. Keep both types in the same teaching file so dotnet run stays simple. Run with dotnet run. The screen should show one line: 4. The number you pass to new reaches the constructor, and the constructor stores it on the object before Main continues. Setting the field at build time — inside the constructor — is what this page teaches. Keep the starting public class named Pine.

A method that runs when new builds

A constructor has the same name as the class. It has no void return type and no other return type. When Main writes new Box(4), C# builds the object and runs that constructor with 4 as n. After the constructor finishes, the variable holds the ready object. That is the whole job of this page: pass a value into new, let the constructor store it on the field, then write the field so you can see the store worked.
Open the Pine file. The starting class name stays Pine. This page does not rename the starter. Delete any c.fill = 3; leftover if that Cup assignment is still all you have in Main. Delete any Cup class leftover. Delete any ReadLine line. The file you keep has no wait for typing.
Outside Pine’s braces — still in the same file — write public class Box. Inside the braces declare int size;. Then write the constructor: Box(int n) { size = n; }. Use a parameter name different from size on this page so the assignment is clear without the word this. There is no Main in Box on this page. Save the file before you run.
The field line alone does not put 4 into the object. The constructor body does that work when new calls it. If you skip the constructor and only declare the field, a later new Box(4) will not match, and the build will complain about the call. Keep both pieces in Box: the field and the constructor that writes into it.

Box with constructor

csharp
using System;

public class Box
{
    int size;

    Box(int n)
    {
        size = n;
    }
}

Pine passes 4 into new Box

Pine keeps public static void Main(). Inside Main, write Box b = new Box(4); then Console.WriteLine(b.size);. The argument 4 goes into the constructor parameter n. You do not need a separate b.size = 4; line on this page — the constructor already stored the value. The write line is there so you can trust what the constructor did without guessing. You are not writing c.fill = 3; on this page. That was the fields lesson.

Pine builds one box

csharp
using System;

public class Pine
{
    public static void Main()
    {
        Box b = new Box(4);
        Console.WriteLine(b.size);
    }
}

public class Box
{
    int size;

    Box(int n)
    {
        size = n;
    }
}

Read the kept file from the top. using System; prepares short names. public class Pine is the starter. public static void Main() is where the runtime starts. The expression new Box(4) builds a Box and calls Box(int n) with n equal to 4. The body writes size = n, so that object’s size becomes 4. Then Main writes b.size and the screen shows 4. Nothing else should print.
Run it with dotnet run. The program writes one line and stops. It does not wait for you to type. If dotnet run waits, ReadLine is still in the file. Delete that line and keep new Box(4) plus the write in Pine, with the constructor in Box. The screen shows 4. If the screen shows 3, a leftover c.fill = 3; path is still running. If the screen shows ok, an old Chip demo may still be in the file. You do not reinstall the .NET SDK for a screen that shows the wrong line.
If you write new Box() with no argument while the only constructor needs an int, the build refuses. Match the call to the constructor’s parameter list. If you add void before the constructor name, it becomes an ordinary method, not a constructor, and new Box(4) will not run that body the way this page expects. The header must look like Box(int n), not void Box(int n), and not static int Box(int n).

Compared with assigning after new

On the fields page you wrote c.fill = 3; after new Cup(). That still works. This page moves the store into the constructor so the value is set while the object is built. A leftover Cup demo with c.fill = 3; is a different lesson. For this page keep Box and Pine and new Box(4). If Pine still has c.fill = 3; and this file has no Cup class, remove that line. The build will not invent a Cup for you.
Writing Console.WriteLine(b); alone does not show a clean 4. Write Console.WriteLine(b.size); to see the stored number. The object reference alone is not the field value. You already learned that pattern on the fields page; keep it here when you check the constructor’s work.
You can still assign a field after new in other programs. This lesson simply chooses the constructor path so the first useful value arrives at build time. Do not mix both styles in the same Pine demo on this page. One clear path is enough: argument to new, store in the constructor, write the field.

Two boxes, two sizes

Each new Box(...) runs the constructor again for a separate object. You can write Box a = new Box(2); and Box b = new Box(9);, then write both size fields. The first call stores 2 on one object. The second call stores 9 on another object. The two objects do not share one size slot.

Pine builds two boxes

csharp
using System;

public class Pine
{
    public static void Main()
    {
        Box a = new Box(2);
        Box b = new Box(9);
        Console.WriteLine(a.size);
        Console.WriteLine(b.size);
    }
}

public class Box
{
    int size;

    Box(int n)
    {
        size = n;
    }
}

Run again with dotnet run. The screen should show 2 on one line and 9 on the next. Each constructor call stored its own argument on its own object. Writing Box b = a; would not build a second object — use two new Box(...) calls when you want two sizes. Copying a reference is not the same as calling the constructor twice.
If both lines show the same number, check that each new passes a different argument and that you write a.size and b.size in that order. If the build stops on the second new, look for a missing parenthesis or a wrong class name left from an older shape. Small typos in the second call are common when you paste the first line and forget to change the argument.

What this leaves for this

This page uses size = n; with different names. A later page — this — shows how to talk about the object’s own field when names collide. Stay with the clear parameter name n here. Do not invent this.size on this page unless you already know it; the lesson goal is the constructor call from new. The word this is the next topic, not a requirement for storing n into size today.
Do not nest Box inside Pine’s braces. On this page the two classes sit as siblings in the file. If the build cannot find Box while compiling Pine, check that public class Box sits in the same file. If the screen shows 0, the constructor may be missing the assignment, or Main may still use a no-arg shape that never sets size — keep Box(int n) { size = n; } and new Box(4). A zero on the screen usually means the field stayed at its default because the store never ran.

You can declare int size;, write Box(int n) { size = n; }, and build with Box b = new Box(4); from Pine.Main. Run with dotnet run. The screen shows 4. The constructor runs when new builds the object. You passed the number at build time, the constructor stored it on the field, and the write proved the store. Think of the constructor as the setup that runs before Main continues past new. Pine stays the door you open with dotnet run. The next page is this, where you learn another way to name the object’s own fields inside its methods and constructors.
Keep the constructor header without void. Keep the argument on new. Keep the write on b.size. Those three habits are the checkpoint for this page before you move on.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top