Creating a List of Two Ints

I have a code that looks like this:

int A = 3; int B = 5; List<int> TheList = new List<int>(); TheList.Add(A); TheList.Add(B); SomeFunction(TheList); 

Is there a way to write something like this:

 SomeFunction((A,B).ToList()); 
+4
source share
2 answers

Yes:

 new List<int>{A, B} 

creates a list with the two elements you specify. You can pass this list to a function or do something else with it.

Note that if your target function accepts IList<int> rather than List<int> , you can shorten the syntax a bit by sending a new array from int s because the T[] arrays implement their corresponding IList<T> interface.

+6
source
 SomeFunction(new List<int> { A, B }); 
+2
source

Source: https://habr.com/ru/post/1440194/


All Articles