c# · level 2 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
One lamp gets brighter. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Lamp desk = new Lamp("desk", 40);
Lamp hall = new Lamp("hall", 60);
desk.Watts = desk.Watts + 20;
Console.WriteLine($"{desk.Place} {desk.Watts}, {hall.Place} {hall.Watts}");
class Lamp
{
public string Place;
public int Watts;
public Lamp(string place, int watts)
{
Place = place;
Watts = watts;
}
}
your turn
Your turn. Finish the constructor.
On lines 12 and 13, copy each parameter into its field. Then give your player a name on line 3 and press run.
output
press run to see what happens
fix it
The pizza order will not go through. Fix it!
output
press run to see what happens
- C# says
CS7036on line 3: an argument is missing. How many parameters does the constructor on line 10 have? - The constructor wants a topping and a size, in that order. Line 3 only gives a topping.
- Change line 3 to
Pizza order = new Pizza("margherita", "large");, then press run.
nailed it
your objects arrive ready to use. :D
- A constructor shares its class's name and has no return type.
- Arguments after
newfill in the fields. - Use
decimalwith anmfor money.
new words in your collection
- constructor
- decimal
This lesson isn’t saved. A free account remembers every lesson you finish.