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 WoofForwarding 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 5All lessons in this course
- Primary Constructors on Classes
- Capturing Parameters in Members
- Primary Constructors with Structs
- Combining with Properties and Bases