title: Resetting lists in c#
body: <p>Following are two pieces of code I used to compute power sets of elements in a list </p>
  
  <p>code 1)   </p>
  
  <pre><code> public static List&lt;List&lt;int&gt;&gt; getCpower(List&lt;int&gt; list)
      {
          var result = new List&lt;List&lt;int&gt;&gt;();
          for (int i = 0; i &lt; (1 &lt;&lt; list.Count); i++)
          { 
              var sublist = new List&lt;int&gt;();
              for (int j = 0; j &lt; list.Count; j++)
              {   if ((i &amp; (1 &lt;&lt; j)) != 0)
                  {   sublist.Add(list[j]); 
                  }
              }
              result.Add(sublist); 
          }
  
          return result;
      }
  </code></pre>
  
  <p>code 2)</p>
  
  <pre><code>public static List&lt;List&lt;int&gt;&gt; getCpower(List&lt;int&gt; list)
      {
          var result = new List&lt;List&lt;int&gt;&gt;();var sublist = new List&lt;int&gt;();
          for (int i = 0; i &lt; (1 &lt;&lt; list.Count); i++)
          { 
              sublist.Clear();sublist.TrimExcess();
              for (int j = 0; j &lt; list.Count; j++)
              {   if ((i &amp; (1 &lt;&lt; j)) != 0)
                  {   sublist.Add(list[j]); 
                  }
              }
              result.Add(sublist); 
          }
  
          return result;
      }
  </code></pre>
  
  <p>The first code used a new statement and if i try to find out powersets of list with count 30 then OutOfMemoryException arises.So to save memory i used Clear() and TrimExcess() to get the list as if it were initialized using a new statement in code2. But these two codes return different results. I do not get why is this happening. Please help.</p>
  
  <p>Are the two following two pieces not doing the same thing</p>
  
  <pre><code>   for(....)   
        {
         var sublist = new List&lt;int&gt;();
         for(......)
             {
              //some code
             }
        }
  </code></pre>
  
  <p>and</p>
  
  <pre><code> var sublist = new List&lt;int&gt;();
   for(.....)
      {
        sublist.Clear();sublist.TrimExcess();
        for(.... )
        {
        //some code 
        }
      }
  </code></pre>