DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

How a decompiler reads a covariant override

C# 9 let you write the override everyone had wanted for twenty years: a Clone() on Dog that returns Dog, not Animal. It reads like a triviality. Underneath it is one of the few places where the C# compiler has to emit metadata the CLR's normal overriding rules forbid, and then patch the runtime's behavior with an attribute to make it safe. For anyone reading a compiled assembly, a covariant override looks alarmingly like an explicit interface implementation — same .override directive, same unusual shape — and getting the two confused produces decompiled code that does not compile. Telling them apart is a pure metadata problem, and a good window into how a decompiler reasons about the vtable.

The real question

The CLR pairs a virtual override with the method it overrides by matching name and full signature, return type included. That is the whole reason overriding "just works" without any explicit wiring. A covariant override breaks the rule on purpose: Dog Clone() and Animal Clone() have different return types, so by the runtime's default logic they are two different methods in two different vtable slots. Yet the language demands that calling Clone() through an Animal reference land on Dog.Clone(). Something has to reclaim the base's slot for a method the runtime would otherwise consider unrelated.

So the question Glass answers is not "what does this override do" but "is this .override record reclaiming a base-class vtable slot for a more-derived return type, or is it implementing an interface method?" Those are the same directive pointing at two different kinds of target, and only the target's metadata tells them apart.

What the compiler actually emits

Start from the source everyone writes:

public class Animal
{
    public virtual Animal Clone() => new Animal();
}

public class Dog : Animal
{
    public override Dog Clone() => new Dog();
}
Enter fullscreen mode Exit fullscreen mode

Dog.Clone returns Dog. In IL, the method keeps the base's name and virtual-ness but cannot reuse the slot by signature, because the signature differs. The compiler emits three things that a normal override never needs:

.method public hidebysig virtual instance class Dog
        Clone() cil managed
{
  .custom instance void [System.Runtime]System.Runtime.CompilerServices.PreserveBaseOverridesAttribute::.ctor() = ( 01 00 00 00 )
  .override method instance class Animal Animal::Clone()
  newobj     instance void Dog::.ctor()
  ret
}
Enter fullscreen mode Exit fullscreen mode

Read the three markers in order. First, the return type on the .method line is Dog, not Animal — that is the whole feature, visible right there in the signature. Second, the .override directive names Animal::Clone() explicitly; this is a row in the MethodImpl table, the same table that records explicit interface implementations. It says "this body implements that slot," overriding the runtime's signature-based pairing by hand. Third, [PreserveBaseOverrides] is stamped on the method so the runtime keeps resolving the most-derived body in that slot even after another subclass derives again.

The crucial detail for a decompiler: there is no newslot flag. The method deliberately reuses the base slot. An explicit interface implementation, by contrast, lives in its own slot and is private final newslot virtual. That single flag, plus what the .override points at, is most of the answer.

A covariant override and an explicit interface implementation share the MethodImpl directive; Glass distinguishes them by what the directive targets.

The recovery heuristic

Glass treats every MethodImpl row as a fork. For the row to be rendered as a covariant override, four facts must hold together — read straight from metadata, no guessing:

  1. The overridden method lives on a base class, not an interface. Resolve the .override target; if its declaring type is an interface, this is an explicit interface implementation and the covariant path ends immediately.
  2. The implementing method and the target share a name and parameter list. Clone() to Clone(), identical parameters. A covariant override cannot rename; a divergence here means something else is going on.
  3. The implementing method's return type is assignable to the target's return type. Dog derives from Animal, so Dog is a legal covariant return for a slot typed Animal. Glass walks the base-type chain (and, for interfaces returned covariantly, the implemented-interface set) to confirm the relationship. If the return types are identical, no covariance is involved and the method would not have needed an explicit .override at all — which is itself a signal the row means something unusual.
  4. The method reuses the base slot (no newslot) and is marked [PreserveBaseOverrides]. This is the runtime's own fingerprint for the feature. Its presence turns a plausible match into a certain one.

When all four hold, Glass drops the .override directive and the attribute from the printed source — they are compiler and runtime bookkeeping, not author intent — and emits the clean line the developer actually wrote:

public override Dog Clone() => new Dog();
Enter fullscreen mode Exit fullscreen mode

The attribute and the MethodImpl are still visible in the IL view for anyone who wants them; they simply do not belong in reconstructed C#, because re-emitting them by hand would be redundant at best and a compile error at worst.

When it is an interface implementation instead

The same shape appears when a class implements an interface method under a different accessibility or to disambiguate two interfaces:

public interface ICloneableAnimal { Animal Clone(); }
public class Cat : ICloneableAnimal
{
    Animal ICloneableAnimal.Clone() => new Cat();   // explicit implementation
}
Enter fullscreen mode Exit fullscreen mode

Here the MethodImpl targets ICloneableAnimal::Clone, the method is private final newslot virtual, and there is no [PreserveBaseOverrides]. Steps 1 and 4 both fail. Glass renders it as Animal ICloneableAnimal.Clone(), fully qualified, which is the only legal C# for an explicit interface member. Confusing the two is the classic decompiler bug: print a covariant override as an explicit implementation and the output names a member that does not exist; print an explicit implementation as a plain override and you change its accessibility and break the type.

Caveats and the honest limit

Covariant returns also work when the return type is an interface that the derived method's return type implements, and across generic instantiations — Glass handles both by resolving the assignability in step 3 through the interface set, not just the base-class chain. The feature is also runtime-gated: it requires RuntimeFeature.CovariantReturnsOfClasses, which means it only appears in assemblies targeting .NET 5+. On older targets the same intent was expressed with a hand-written protected virtual Animal CloneCore() plus a new Dog Clone() shadow, and Glass will faithfully show you that pattern — it cannot invent a covariant override that the compiler never emitted.

The one genuinely undecidable case is an explicit override that renames while narrowing the return type through non-public MethodImpl plumbing a non-C# language emitted. There is no C# syntax that both renames and covariantly overrides, so Glass falls back to the explicit, fully-qualified form. That keeps the output compilable, which is the rule that trumps elegance every time.

Takeaway

A covariant override is the rare C# feature that cannot be expressed in the CLR's ordinary overriding model, so the compiler reaches for the same explicit-override machinery that interfaces use and then stabilizes it with [PreserveBaseOverrides]. A decompiler that reads only the .override directive will mistake it for an interface implementation; Glass.NET reads what the directive targets — a base class, a supertype return, a reused slot — and recovers the single clean override line the author wrote, leaving the runtime's bookkeeping where it belongs, in the IL view. Knowing which of those two readings you are looking at is the difference between decompiled code that rebuilds and decompiled code that merely looks plausible.

Top comments (0)