Skip to content

12.7.7.2 and 12.18.2 Array access evaluation order for assignments #169

@jskeet

Description

@jskeet

13.7.7.2 (array access) suggests that evaluating an array access expression performs nullity and index checks.

13.18.2 (simple assignment) states for an assignment x = y:

  • If x is classified as a variable:
    • x is evaluated to produce the variable.
    • y is evaluated and, if required, converted to the type of x through an implicit conversion (§12.2).

That all sounds fine, but my understanding of reality is that the nullity check and array index check are only performed after y is evaluated. Sample code to show that...

Null check comes after RHS

using System;

public class Test
{
    static void Main()
    {
        int[] array = null;
        array[10] = SideEffect(); // Prints "Side effect" then throws
    }

    private static int SideEffect()
    {
        Console.WriteLine("Side effect");
        return 10;
    }
}

Index check comes after RHS

using System;

public class Test
{
    static void Main()
    {
        int[] array = new int[5];
        array[10] = SideEffect(); // Prints "Side effect" then throws
    }

    private static int SideEffect()
    {
        Console.WriteLine("Side effect");
        return 10;
    }
}

I have very vague recollections of this being properly specified somewhere, but I can't easily find it - and assuming it does exist, I think we should have a reference to it within at least one of these sections.

Assigning to Mads initially as he may well know what's going on...

Metadata

Metadata

Assignees

Labels

meeting: discussThis issue should be discussed at the next TC49-TG2 meetingresolved: known-deviationWe know Roslyn deviates from the spec, but we don't want to change the specstatus: gnarlyThis issue is likely to require very significant work to resolvetype: bugThe Standard does not describe the language as intended or implemented

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions