×

c# · level 2 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A fills in each new object as it is built.

Setting every field one line at a time is slow, and you might forget one. A constructor is a method that runs as each new object is built. It has the same name as the class and no return type, not even void.

new Product("tea", 2.50m) hands the name and price to the constructor, which copies them into the fields. Once a class has this constructor, C# insists on both arguments: leave one out and it refuses with CS7036.

The price is a , a number type made for money that keeps pennies exact. Write an m after the number, like 2.50m.

using System;

Product tea = new Product("tea", 2.50m);
Product cake = new Product("cake", 3.25m);
Console.WriteLine($"{tea.Name} costs {tea.Price}");
Console.WriteLine($"{cake.Name} costs {cake.Price}");

class Product
{
    public string Name;
    public decimal Price;
    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;
    }
}

A decimal remembers how it was written, so 2.50m prints as 2.50.