Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<int> in c#

Tags:

c#

.net

reference

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.

  1. 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.
  2. But 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;
        }
    }
}
like image 485
Prashant Avatar asked Jul 08 '10 22:07

Prashant


2 Answers

List is supposed to be of value type and not reference type.

Wrong! int is a value type. List<int> is a reference type.

like image 111
Joel Coehoorn Avatar answered Oct 19 '22 16:10

Joel Coehoorn


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);
      }
   }
}
like image 30
mattmc3 Avatar answered Oct 19 '22 16:10

mattmc3