Skip to content

Missing readonly on ref-local can result in ArrayTypeMismatchException #3237

Description

@dgrunwald

Input code

using System.Collections.Generic;

public class C {
    public static void Foo(in object a, object v) {}
    public static void M1(object[] arr) {
        Foo(in arr[1], new List<int>{1,2});
    }
    public static void Main() {
        string[] arr = new string[5];
        M1(arr);
    }
}

Erroneous output

If collection initializers are disabled, or if the second argument is another complex expression that the decompiler transforms into multiple statements:

    public static void M1(object[] arr)
    {
        ref object a = ref arr[1];
        List<int> list = new List<int>();
        list.Add(1);
        list.Add(2);
        Foo(ref a, list);
    }

In the original code, in arr[1] translates to readonly.ldelema. In the decompiled code, we get a non-readonly ldelema. This results in the decompiled program failing with ArrayTypeMismatchException when the original program was successful.

A correct decompilation would use:

    public static void M1(object[] arr)
    {
        ref readonly object a = ref arr[1];
        List<int> list = new List<int>();
        list.Add(1);
        list.Add(2);
        Foo(in a, list);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugDecompilerThe decompiler engine itself

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions