Skip to content

Missing parentheses around field assignment expression in list initializers #3543

@mmusu3

Description

@mmusu3

Input code

class AssignmentInCollectionInitializerTest
{
    int dataField;

    object Test()
    {
        return new int[] { dataField = 1 };
    }

    object Test2()
    {
        return new List<int> { (dataField = 1) };
        // Alternate syntax
        //return new List<int> { { dataField = 1 } };
    }

    object Test3()
    {
        return new Dictionary<int, int> { [0] = dataField = 1 };
    }

    object Test4()
    {
        return new Dictionary<int, int> { { 0, dataField = 1 } };
    }

    object Test5()
    {
        return new CustomCollection { (dataField = 1) };
        // Alternate syntax
        //return new CustomCollection { { dataField = 1 } };
    }

    class CustomCollection : IEnumerable<int>
    {
        public void Add(int value) { }
        public IEnumerator<int> GetEnumerator() => null;
        IEnumerator IEnumerable.GetEnumerator() => null;
    }
}

Erroneous output

using System.Collections;
using System.Collections.Generic;

internal class AssignmentInCollectionInitializerTest
{
	private int dataField;

	private object Test()
	{
		return new int[1] { dataField = 1 };
	}

	private object Test2()
	{
		// Error CS0117: 'List<int>' does not contain a definition for 'dataField'
		return new List<int> { dataField = 1 };
	}

	private object Test3()
	{
		return new Dictionary<int, int> { [0] = (dataField = 1) };
	}

	private object Test4()
	{
		return new Dictionary<int, int> { 
		{
			0,
			dataField = 1
		} };
	}

	private object Test5()
	{
		// Error CS0117: 'AssignmentInCollectionInitializerTest.CustomCollection' does not contain a definition for 'dataField'
		return new CustomCollection { dataField = 1 };
	}

	private class CustomCollection : IEnumerable<int>, IEnumerable
	{
		public void Add(int value)
		{
		}

		public IEnumerator<int> GetEnumerator()
		{
			return null;
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return null;
		}
	}
}

Details

Tested at commit 587a359

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugDecompilerThe decompiler engine itself

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions