0Pricing
C# Academy · Lesson

Combining with Properties and Bases

Forward parameters to base types and properties.

Combining Primary Constructors with Inheritance

A derived class with a primary constructor can forward its parameters to a base class using the : Base(args) syntax in the header.

using System;

class Animal(string name) {
    public string Name => name;
}

class Dog(string name) : Animal(name) {
    public string Speak() => Name + " says Woof";
}

Console.WriteLine(new Dog("Rex").Speak()); // Rex says Woof

Forwarding a Subset of Parameters

The derived class can take more parameters than the base and pass only the relevant ones upward.

using System;

class Shape(string color) {
    public string Color => color;
}

class Box(string color, int size) : Shape(color) {
    public int Size => size;
}

var b = new Box("red", 5);
Console.WriteLine(b.Color + " " + b.Size); // red 5

All lessons in this course

  1. Primary Constructors on Classes
  2. Capturing Parameters in Members
  3. Primary Constructors with Structs
  4. Combining with Properties and Bases
← Back to C# Academy