C# > Language Features by Version > C# 6 to C# 12 Highlights > Primary Constructors (C# 12)

Primary Constructors and Inheritance

This example shows how primary constructors interact with inheritance in C# 12. It demonstrates how a derived class can call the primary constructor of a base class.

Code Example

The `Animal` class defines a primary constructor with a `name` parameter. The `Dog` class, which inherits from `Animal`, also defines a primary constructor with `name` and `breed` parameters. The `Dog` constructor calls the `Animal` constructor using `: Animal(name)`, passing the `name` parameter. This ensures that the `Animal` class is properly initialized. The `Breed` property of the `Dog` class is initialized directly from the `breed` constructor parameter.

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

    public virtual string MakeSound() => "Generic animal sound";
}

public class Dog(string name, string breed) : Animal(name)
{
    public string Breed { get; } = breed;

    public override string MakeSound() => "Woof!";
}

How Inheritance Works with Primary Constructors

When a derived class uses a primary constructor and inherits from a base class that also uses a primary constructor, the derived class *must* explicitly call the base class constructor in its own constructor. This is done using the `: base(...)` syntax, passing any necessary parameters to the base class constructor. If the base class does not have a constructor (like the implicit parameterless constructor), then `: base()` is not needed.

Real-Life Use Case

Consider a hierarchy of UI controls. A base `Control` class might have properties like `Width` and `Height`, and derived classes like `Button` or `TextBox` might have additional properties specific to their type. Primary constructors can cleanly handle the initialization of these properties in each class, while ensuring proper initialization of the base class.

Interview Tip

Be prepared to explain how primary constructors simplify class definitions and how they interact with inheritance. Understanding the `: base(...)` syntax is crucial for demonstrating your knowledge of object-oriented programming in C#.

Alternatives

Prior to C# 12, this could have been achieved with explicit constructors and field initializers. While functionally equivalent, primary constructors provide a more concise and readable alternative.

FAQ

  • What happens if the derived class doesn't call the base class constructor?

    The compiler will generate an error, indicating that the base class constructor needs to be called explicitly.
  • Can a derived class add additional logic to its primary constructor?

    Yes, but it is recommended to minimize complex logic within primary constructors to maintain readability. You can initialize properties or call methods as needed, but extensive calculations or conditional logic should be placed elsewhere.