DynamicExpresso
DynamicExpresso copied to clipboard
Support for List construction with values
Would be possible to support syntax like this?....
new List<int>() { 1, 2, 3 }
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 hasAdd
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 }
Supporting array initializer would be great as well
new int[]{ 1, 2, 3}
@davideicardi @metoule Any advice on how to add this feature?
Closed by #250 ! Thank you @holdenmai and @metoule !