skip to content

In C# 9 and later, can an override of Notification Clone() return EmailNotification, and what limits apply to covariant returns?

level: middleimportance: nice to knowfreq 25%

answer

  1. C# 9 relaxed the exact-match rule
  2. reference conversions only
  3. read-only properties, not settable ones
  4. needs .NET 5 runtime support

basics

~20 s

Yes. Since C# 9 an override may return a more derived reference type, so callers holding an EmailNotification get EmailNotification without a cast. It needs .NET 5 or later and works for methods and read-only properties, not value types or setters.

solid answer

~30 s

C# 9 added covariant return types: `public override EmailNotification Clone()` may override `public abstract Notification Clone()`. Callers whose static type is `EmailNotification` get `EmailNotification` back; through a `Notification` variable the call is still typed `Notification`, but the same override runs. The override's type must convert by an implicit reference conversion, so `int` overriding `object` is CS0508. Only read-only properties may narrow their type; a settable one is CS1715. Further overrides must be at least as specific. The compiler emits a new slot with `PreserveBaseOverridesAttribute`, which needs runtime support from .NET 5 on; older targets report CS8830.

code

csharp · 16 lines
csharp
EmailNotification original = new() { Subject = "Invoice" };
EmailNotification copy = original.Clone();   // no cast: the override returns EmailNotification
Notification viaBase = original;
Notification baseCopy = viaBase.Clone();      // static type Notification, runtime type EmailNotification
Console.WriteLine($"{copy.Subject} {baseCopy.GetType().Name}");

abstract class Notification
{
    public abstract Notification Clone();
}

class EmailNotification : Notification
{
    public string Subject { get; init; } = "";
    public override EmailNotification Clone() => new() { Subject = Subject };
}

go deeper

for a junior

Recall that since C# 9 an override such as Clone() may return the derived class, which saves a cast for callers who already hold that class.

for a middle

Explain the limits: implicit reference conversions only, read-only properties only, later overrides at least as specific, and the static type seen through a base-typed variable.

for a senior

Know that the feature needs runtime support from .NET 5 on (CS8830 or CS8831 otherwise) and check this before adding covariant overrides to a library that still targets older frameworks.

for a principal

Decide whether a public hierarchy's copy and factory members should use covariant returns, weighing fewer casts for callers against binding every derived library to runtimes that support it.

## The rule since C# 9 Before C# 9 an override had to repeat the base method's return type exactly. A `Notification` hierarchy with `public abstract Notification Clone()` forced `EmailNotification.Clone()` to return `Notification`, and every caller who knew it held an email had to cast the copy back. C# 9 added **covariant return types**: an override may declare a **more derived return type** than the member it overrides. ```csharp abstract class Notification { public abstract Notification Clone(); } class EmailNotification : Notification { public override EmailNotification Clone() => new(); } ``` Callers then get the refined type **statically**: - through an `EmailNotification` variable, `Clone()` has type `EmailNotification`, so no cast is needed; - through a `Notification` variable, the call still has type `Notification`, because the compiler binds to the member it finds on that static type; - in both cases dispatch runs `EmailNotification.Clone` and the object returned is an `EmailNotification`. ## The limits The relaxation is narrower than "any compatible type": 1. **Implicit reference conversion only.** The override's return type must convert to the base return type by an identity or implicit **reference** conversion: a class derived from the base return type or, when the base returns an interface, a reference type that implements it. A value type is not covariant with `object`: overriding `object Priority()` with `int Priority()` is **CS0508**, "return type must be 'object' to match overridden member", because `int` to `object` is a boxing conversion. 2. **Methods and read-only properties.** A property or indexer can be covariant only when it is read-only. Overriding a `get; set;` property of type `Notification` with one of type `EmailNotification` is **CS1715**, "type must be 'Notification' to match overridden member". The setter would otherwise accept only emails where the base contract accepts any notification. 3. **No ref returns.** The rule covers value returns, not `ref` returns. 4. **Overrides stay at least as specific.** A class below `EmailNotification` that overrides `Clone()` again must return `EmailNotification` or something more derived, not fall back to `Notification`. 5. **Accessibility.** The narrower return type must be at least as accessible as the override that returns it, so a `public` override in a `public` type needs a `public` return type. ## Why it needs runtime support | Target | Covariant override | |---|---| | .NET 5 or later (including .NET 10) | Compiles and runs | | .NET Framework, .NET Core 3.1 or older | Error **CS8830** (methods) or **CS8831** (properties): the target runtime doesn't support it | The feature is not pure syntax. In compiled code an ordinary override has to match the base method's signature, return type included, so the compiler emits a covariant override as a **new method slot** that explicitly overrides the base method, and marks it with `PreserveBaseOverridesAttribute` so that calls through the base method keep reaching the most derived override. Older runtimes do not understand that combination. The runtime advertises the capability as `RuntimeFeature.CovariantReturnsOfClasses`, and on a target without it the compiler refuses with CS8830 or CS8831 rather than producing broken code. ## When it matters in practice - **Copy and factory methods** such as `Clone()` or `WithSubject(...)` on a class hierarchy, where callers already hold the derived type. - **Navigation properties** that are read-only and naturally narrower in a subclass, such as an `Owner` property typed more specifically in a derived class. - It removes casts; it does **not** change what runs. Dispatch was already reaching the derived method before C# 9. Things it does not do: - It does not apply to parameters; parameter types must still match exactly. - It does not change interfaces' generic variance (`out T`), which is a separate feature with its own rules. - It does not turn `new` hiding into overriding; hiding a method with a narrower return type is still a second, separate member. ## A quick self-test Given `public virtual object Describe()` in a base class, which overrides compile? `public override string Describe()` does, since `string` is a reference type that converts to `object`. `public override int Describe()` does not, with CS0508. A settable `object Value { get; set; }` cannot be narrowed to `string` in an override, with CS1715.

  • What does a call through a Notification-typed variable return when the override is covariant?
    The expression's static type stays `Notification`, because the compiler binds to the member it finds on the receiver's static type. The object returned is still whatever the override created, an `EmailNotification`, since dispatch picks the override at run time. Covariance changes what the compiler knows, not what runs.
  • Why can't a settable property narrow its type in an override?
    The setter takes the property type as input. If `EmailNotification Target { get; set; }` overrode `Notification Target { get; set; }`, base-typed code could legally assign any `Notification` through a slot that now accepts only emails. C# allows the narrowing only on read-only properties and reports CS1715 otherwise.

  • Says an override must always repeat the base return type exactly, in every C# version.
  • Believes a value type such as int can override an object-returning method.
  • Thinks covariant returns also let a settable property narrow its type.
  • Claims covariant returns change which method runs rather than only the static type.
  • Expects covariant overrides to compile for any target framework.