Cast lost when ternary with mismatched branch types is hoisted to `object` local

Aperta
#3,736 3 commenti 1 reazione 1 assegnatario Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@siegfriedpammer ci sta già lavorando.

Dal 27/8/2026.

Valutazione

Questa issue non è ancora stata valutata.

Descrizione

Bug Feedback Needed

When a ?:'s two branches have different stack types and ILSpy can't find a common type tighter than object, it hoists the conditional into an if/else with an object obj local — but drops the explicit cast that was present in the source. The dropped cast can re-bind to a different overload on recompile.

Repro
using System.Collections.Generic;
using System.Linq;

public class Repro
{
    public IEnumerator<byte> Bug(byte[] data, bool reversed)
        => (reversed ? ((IEnumerable<byte>)data).Reverse() : (IEnumerable<byte>)data).GetEnumerator();
}
ilspycmd 10.0.1.8346 output
public IEnumerator<byte> Bug(byte[] data, bool reversed)
{
    object obj;
    if (!reversed)
    {
        obj = data;
    }
    else
    {
        obj = data.Reverse();  // (IEnumerable<byte>) cast lost
    }
    return ((IEnumerable<byte>)obj).GetEnumerator();
}

When a project-local void Reverse(this byte[]) (or similar shadowing extension) is in scope, data.Reverse() re-binds to it on recompile → CS0029 ("Cannot implicitly convert type 'void' to 'object'"). Even without a shadow, the decompile is semantically lossy.

dotPeek emits the inline ternary form with both casts preserved.

Related

#1501, #1614, #3322, #3464, #793 are all in the same family (ILSpy dropping a needed cast); none is exactly this ?:→if/else hoist variant.

Lingua principale
C#
Stelle
27.1k
Fork
3.8k
Merge medio
1g 23h
PR unite (30g)
44

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di icsharpcode/ILSpy

Tutte le issue di icsharpcode/ILSpy

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.