Adding primitive struct
(eg. int
) to a List
:
int i=10;
List<int> list=new List<int>();
list.Add(i);
Versus:
Adding non-primitive struct
(eg. KeyValuePair<int,int>
) to a list:
List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>();
list.Add(new KeyValuePair<int,int>(10,20));
While adding the int
struct
to a list
, we do not need to use the new
keyword. But while adding the KeyValuePair
struct
to a list, we need to use the new
keyword.
I mean to say, the following statement is not valid:
list.Add(new int(10)); //invalid statement
Though both int
and KeyValuePair
are struct's, they behave differently - one does not require instantiation before use (as far as the user is concerned). And the other requires instantiation before use.
Why can't we do the following instead:
list.Add(KeyValuePair<int,int>(10,20)) //omit the new keyword, as we were doing with an int
Coming from a C/C++ background, what does the new
keyword exactly do in C#?
Does it just instantiate the underlying data type (and we are not sure whether the instantiated data type will lie on the Stack or the Heap). Or, are we sure that using the new keyword will allocate memory on the Heap (as it does in C++)?