DynamicExpresso icon indicating copy to clipboard operation
DynamicExpresso copied to clipboard

Support for List construction with values

Open waclaw66 opened this issue 2 years ago • 2 comments

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

waclaw66 avatar Nov 25 '21 08:11 waclaw66

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 }

metoule avatar Nov 25 '21 08:11 metoule

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

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

israellot avatar Aug 08 '22 23:08 israellot

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

davideicardi avatar Sep 26 '22 10:09 davideicardi