← C# from Scratch
Lesson 29 of 39 · 10 XP
Constructors
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A constructor is a method that is called on new. Its name is the same as the class's, and it has no return type:
class Enemy
{
public string Name;
public int Hp;
public Enemy(string name, int hp) // a constructor
{
Name = name;
Hp = hp;
}
public Enemy(string name) : this(name, 100) { } // a second one that calls the first
}
var orc = new Enemy("Orc", 50);
var boss = new Enemy("Dragon"); // Hp = 100
- if you don't write a constructor, the class has an empty "default" one; once you write your own, the empty one is gone;
- a constructor guarantees that the object is in a valid state straight away;
- C# 12 has a short form — a primary constructor:
class Point(int x, int y) { … }.
Task. Write a class Rectangle with the constructors Rectangle(int w, int h) and Rectangle(int side)
(a square) and the methods Area() and Perimeter(). Input: one line with one or two numbers.
Print <area> <perimeter>.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.