Skip to content
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

Support for List construction with values #194

Closed
waclaw66 opened this issue Nov 25, 2021 · 3 comments
Closed

Support for List construction with values #194

waclaw66 opened this issue Nov 25, 2021 · 3 comments

Comments

@waclaw66
Copy link

Would be possible to support syntax like this?....
new List<int>() { 1, 2, 3 }

@metoule
Copy link
Contributor

metoule commented Nov 25, 2021

Relevant C# documentation: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers

Collection initializers let you specify one or more element initializers when you initialize a collection type that implements
IEnumerable and has Add with the appropriate signature as an instance method or an extension method. The element initializers can be a simple value, an expression, or an object initializer.

new List<int>() { 1, 2, 3 }

is equivalent to:

List<int> list = new List<int>();
list.Add (1);
list.Add (2);
list.Add (3);

If the wanted Add method has multiple parameters, it's possible to specify them. For example, for a Dictionary:

var moreNumbers = new Dictionary<int, string>
{
    {19, "nineteen" },
    {23, "twenty-three" },
    {42, "forty-two" }
};

is equivalent to:

var moreNumbers = new Dictionary<int, string>();
moreNumbers .Add(19, "nineteen");
moreNumbers .Add(23, "twenty-three");
moreNumbers .Add(42, "forty-two");

I also learned that you can use indexers!!

var numbers = new Dictionary<int, string>
{
    [7] = "seven",
    [9] = "nine",
    [13] = "thirteen"
};

To be complete, we should probably also allow the creation of an Array:

new int[] { 1, 2, 3 }

@israellot
Copy link
Contributor

israellot commented Aug 8, 2022

Supporting array initializer would be great as well
new int[]{ 1, 2, 3}

@davideicardi @metoule Any advice on how to add this feature?

@davideicardi
Copy link
Member

Closed by #250 ! Thank you @holdenmai and @metoule !

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

No branches or pull requests

4 participants