New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strange behaviour with Dictionary and List initializers in C# 6 #18475

Closed
ksmigiel opened this Issue Apr 5, 2017 · 1 comment

Comments

Projects
None yet
3 participants
@ksmigiel

ksmigiel commented Apr 5, 2017

Version Used:
Roslyn 2.0.0-rc2 (C# 6)

Steps to Reproduce:

Run below code

var dictionary = new Dictionary<int, List<int>>
{
	[0] = new List<int>{ 1 },
	[0] = { 2 }
};
		
Console.WriteLine(dictionary[0].Count);

Expected Behavior:
Compiler or static code analysis should raise an error, since it looks like not supported syntax.

Actual Behavior:
Dictionary will contain List with two elements {1, 2}

What's more case below is also compiled without problems, but during execution KeyNotFoundException exception will be thrown:

var dictionary = new Dictionary<int, List<int>>
{
	[0] = { 1 }
};

I found it by mistake and then by analyzing generated IL code

@jaredpar

This comment has been minimized.

Show comment
Hide comment
@jaredpar

jaredpar Jun 16, 2017

Member

Thanks for taking the time to report this issue. This is fairly similar to #19739 and you may want to read that discussion.

But essentially what is happening here is you're mixing member and collection initializers. The behavior there is covered by this section of the spec:

A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the target field, property or indexer, the elements given in the initializer are added to the collection referenced by the target. The target must be of a collection type that satisfies the requirements specified in §7.6.11.3.

Member

jaredpar commented Jun 16, 2017

Thanks for taking the time to report this issue. This is fairly similar to #19739 and you may want to read that discussion.

But essentially what is happening here is you're mixing member and collection initializers. The behavior there is covered by this section of the spec:

A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the target field, property or indexer, the elements given in the initializer are added to the collection referenced by the target. The target must be of a collection type that satisfies the requirements specified in §7.6.11.3.

@jaredpar jaredpar closed this Jun 16, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment