typestar

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

  1. The constructor takes radius and an optional name.
  2. Get-only properties are assigned there and never again.
  3. Area is computed on demand from Radius, not stored.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Classes & records, step 19 of 29 in Language basics.

← Previous Next →