I am unable to understand the logic behind List<int>
as it breaks some of the basic rules.
List<int>
is supposed to be of value type and not reference type.
List<int>
has to be passed by ref
keyword if its value has to be persisted between function calls. So this means it is displaying a value type behavior similar to int.List<int>
has to be initialized by a new operator. Also List<int>
could be null as well. This implies a reference type behavior. A nullable type is different as in it does not have to be initialized by new operator.
Am I seeing something wrong here?
EDITED-
I should have posted the code in the original question itself. But it follows here -
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ListTest d = new ListTest();
d.Test();
}
}
class ListTest
{
public void ModifyIt(List<int> l)
{
l = returnList();
}
public void Test()
{
List<int> listIsARefType = new List<int>();
ModifyIt(listIsARefType);
Console.WriteLine(listIsARefType.Count); // should have been 1 but is 0
Console.ReadKey(true);
}
public List<int> returnList()
{
List<int> t = new List<int>();
t.Add(1);
return t;
}
}
}
List is supposed to be of value type and not reference type.
Wrong! int
is a value type. List<int>
is a reference type.
I think you have a faulty assumption in your first bullet. The generic List object is definitely a reference type (on the heap, not the stack). Not sure why you think you have to pass via ref
. This prints "2" like it should:
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
List<int> listIsARefType = new List<int>();
ModifyIt(listIsARefType);
ModifyIt(listIsARefType);
Console.WriteLine(listIsARefType.Count); // 2!
Console.ReadKey(true);
}
static void ModifyIt(List<int> l) {
l.Add(0);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With