Constructors in C#
How an object insists on the data it cannot exist without.
var plain = new Circle(2.0);
var unit = new Circle(1.0, "unit");
Console.WriteLine($"{plain.Name}: {plain.Area:F2}");
Console.WriteLine($"{unit.Name}: {unit.Area:F2}");
class Circle
{
public string Name { get; }
public double Radius { get; }
public double Area => Math.PI * Radius * Radius;
public Circle(double radius, string name = "circle")
{
Radius = radius;
Name = name;
}
}
How it works
- The constructor takes
radiusand an optionalname. - Get-only properties are assigned there and never again.
Areais computed on demand fromRadius, not stored.
Keywords and builtins used here
Circleclassdoublegetnewpublicstringvar
The run, in numbers
- Lines
- 17
- Characters to type
- 381
- Tokens
- 85
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 60 seconds.
Step 2 of 4 in Classes & records, step 19 of 29 in Language basics.