'List<long> testList = new List<long>(id) gives error in C#
long id= 10;
List<long> testList = new List<long>(id); /*creating to List of long */
Above statement gives error in C# and intelligence saying to convert it to int. At the same time when i do it like below it is working as expected.
long id= 10;
List<long> testList = new List<long>(); /*creating to List of long */
testList.Add(id);
what is the reason behind it?
Solution 1:[1]
List initialization (probably want you want to do) is done like this in C#:
long id = 10;
List<long> testList = new List<long>() { id };
Inside the curly brackets you can put multiple elements separated by comma which the list shall initially contain.
Solution 2:[2]
There are 3 constructors for the List class.
public List()
public List(IEnumerable<T> collection)
public List(int capacity)
You are trying to initialize the list using the constructor that takes capacity (which should be int
, not long
).
List.Add()
method adds data to the list. So, your statement of creating list object v/s adding element to list is what giving you the error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Danitechnik |
Solution 2 |