<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7162964</id><updated>2011-07-30T22:27:06.013-07:00</updated><title type='text'>John Franco</title><subtitle type='html'>Supposedly this blog will be about programming problems that interest me.  Right now it seems like these all have something to do with hacking the C# host.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://buiba.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://buiba.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>johnnycrash</name><uri>http://www.blogger.com/profile/00685855809394991386</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>5</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7162964.post-9196888918933960230</id><published>2009-06-17T03:57:00.001-07:00</published><updated>2009-06-17T04:02:33.454-07:00</updated><title type='text'>High Performance Method to Copy C# KeyedCollection&lt;,&gt;, List&lt;&gt;, and Dictionary&lt;,&gt;</title><content type='html'>&lt;p&gt;What do you do if you have a collection with 1,000,000 items in it and you want to make a quick copy?&amp;#160; C# says you should loop through the source collection and call .add() on the destination collection, but what if that is just waaaaaaaaaaaaay toooooooooooo sloooooooow?&lt;/p&gt;  &lt;p&gt;You could write some unsafe code to get the job done.&amp;#160; What I did here was make some structures that contained all the instance variables of the aforementioned classes.&amp;#160; I then overlaid these structures on top of their classes so I can gain access to the private member variables.&amp;#160; Once inside a List&amp;lt;&amp;gt;, I just use Array.Copy to copy the internal array that makes up the List&amp;lt;&amp;gt;.&amp;#160; There are a couple more variables that have to be copied like the number of elements currently in use in the array, etc.&amp;#160; I do the same sort of thing with Dictionary&amp;lt;,&amp;gt; and KeyedCollection.&amp;#160; KeyedCollection actually calls the CopyList and CopyDict functions.&lt;/p&gt;  &lt;p&gt;WARING!!!!!! If you don’t like unsafe code and hacking the C# host, then turn back now.&lt;/p&gt;  &lt;p&gt;WARNING!!!!! This is for 32 bit only.&amp;#160; For 64 bit, we have to switch from int to Int64 when dealing with addresses.&amp;#160; I used a wacky way of getting around the C# casting complaints.&amp;#160; I used an integer pointer that I pointed to the stack.&amp;#160; By using array indexing [] on this pointer, I gained unchecked read/write access to the stack, which is where all the local variables live.&amp;#160;&amp;#160; I can even change where managed objects point without C# complaining!!!&amp;#160; I don’t recommend changing them to point to just anything…&amp;#160; Hilarity will ensue.&amp;#160; Some reader out there might know a better way to do this.&lt;/p&gt;  &lt;p&gt;WARNING!!!! This is for Windows Only.&amp;#160; Don’t try this on Mono.&amp;#160; Well you can, but expect to change the code a bit.&lt;/p&gt;  &lt;p&gt;WARNING!!!! I tested this is for Net 3.5.&amp;#160; The layout of the instance variables of the classes might be different in 2.0 and 3.0.&amp;#160; Also, at any time, Redmond can release a patch and change the layout of these classes.&amp;#160; Hopefully they won’t, but don’t be surprised if they do.&amp;#160; &lt;/p&gt;  &lt;p&gt;Warnings aside, if you have a performance problem related to copying collections, this will solve them.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;&lt;span style="color: #400080"&gt;System&lt;/span&gt;;
&lt;span style="color: blue"&gt;using &lt;/span&gt;&lt;span style="color: #400080"&gt;System&lt;/span&gt;.&lt;span style="color: #400080"&gt;Collections&lt;/span&gt;.&lt;span style="color: #400080"&gt;Generic&lt;/span&gt;;
&lt;span style="color: blue"&gt;using &lt;/span&gt;&lt;span style="color: #400080"&gt;System&lt;/span&gt;.&lt;span style="color: #400080"&gt;Text&lt;/span&gt;;
&lt;span style="color: blue"&gt;using &lt;/span&gt;&lt;span style="color: #400080"&gt;System&lt;/span&gt;.&lt;span style="color: #400080"&gt;Runtime&lt;/span&gt;.&lt;span style="color: #400080"&gt;InteropServices&lt;/span&gt;;
&lt;span style="color: blue"&gt;using &lt;/span&gt;&lt;span style="color: #400080"&gt;System&lt;/span&gt;.&lt;span style="color: #400080"&gt;Collections&lt;/span&gt;.&lt;span style="color: #400080"&gt;ObjectModel&lt;/span&gt;;
&lt;span style="color: blue"&gt;using &lt;/span&gt;&lt;span style="color: #400080"&gt;System&lt;/span&gt;.&lt;span style="color: #400080"&gt;Reflection&lt;/span&gt;;

&lt;span style="color: blue"&gt;namespace &lt;/span&gt;&lt;span style="color: #400080"&gt;CopyCollection &lt;/span&gt;{

  &lt;span style="color: green"&gt;// these are just some test classes that get copied in 
  // the main()
  &lt;/span&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CFoo &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;&lt;span style="color: #400080"&gt;Key&lt;/span&gt;;
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;&lt;span style="color: #400080"&gt;Name&lt;/span&gt;;
  }
  &lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyKeyedCollection &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;KeyedCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;CFoo&lt;/span&gt;&amp;gt; {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #400080"&gt;MyKeyedCollection&lt;/span&gt;() : &lt;span style="color: blue"&gt;base&lt;/span&gt;(&lt;span style="color: blue"&gt;null&lt;/span&gt;, 10) { }
    &lt;span style="color: blue"&gt;protected override int &lt;/span&gt;&lt;span style="color: #400080"&gt;GetKeyForItem&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;CFoo &lt;/span&gt;&lt;span style="color: #400080"&gt;foo&lt;/span&gt;) {
      &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #400080"&gt;foo&lt;/span&gt;.&lt;span style="color: #400080"&gt;Key&lt;/span&gt;;
    }
  }
  &lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyObject &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyKeyedCollection &lt;/span&gt;&lt;span style="color: #400080"&gt;kc&lt;/span&gt;;
    &lt;span style="color: green"&gt;// Copy constructor
    &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #400080"&gt;MyObject&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;MyObject &lt;/span&gt;&lt;span style="color: #400080"&gt;that&lt;/span&gt;) {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.&lt;span style="color: #400080"&gt;kc &lt;/span&gt;= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyKeyedCollection&lt;/span&gt;();
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: #400080"&gt;that &lt;/span&gt;!= &lt;span style="color: blue"&gt;null&lt;/span&gt;) {
        &lt;span style="color: #2b91af"&gt;CollectionTools&lt;/span&gt;.&lt;span style="color: #400080"&gt;CopyKeyedCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;CFoo&lt;/span&gt;&amp;gt;(
         &lt;span style="color: #400080"&gt;that&lt;/span&gt;.&lt;span style="color: #400080"&gt;kc&lt;/span&gt;, &lt;span style="color: blue"&gt;this&lt;/span&gt;.&lt;span style="color: #400080"&gt;kc&lt;/span&gt;);
      }
    }
  }
  &lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program &lt;/span&gt;{

    &lt;span style="color: blue"&gt;static void &lt;/span&gt;&lt;span style="color: #400080"&gt;Main&lt;/span&gt;(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] &lt;span style="color: #400080"&gt;args&lt;/span&gt;) {

      &lt;span style="color: green"&gt;// here I create an object, containing a 
      // keyedcollection with 7 items
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyObject &lt;/span&gt;&lt;span style="color: #400080"&gt;mobj1 &lt;/span&gt;= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyObject&lt;/span&gt;(&lt;span style="color: blue"&gt;null&lt;/span&gt;);
      &lt;span style="color: blue"&gt;for &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;&lt;span style="color: #400080"&gt;i &lt;/span&gt;= 0; &lt;span style="color: #400080"&gt;i &lt;/span&gt;&amp;lt; 7; ++&lt;span style="color: #400080"&gt;i&lt;/span&gt;)
        &lt;span style="color: #400080"&gt;mobj1&lt;/span&gt;.&lt;span style="color: #400080"&gt;kc&lt;/span&gt;.&lt;span style="color: #400080"&gt;Add&lt;/span&gt;(
          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CFoo&lt;/span&gt;() { 
            &lt;span style="color: #400080"&gt;Key &lt;/span&gt;= &lt;span style="color: #400080"&gt;i&lt;/span&gt;, &lt;span style="color: #400080"&gt;Name &lt;/span&gt;= &lt;span style="color: #400080"&gt;i&lt;/span&gt;.&lt;span style="color: #400080"&gt;ToString&lt;/span&gt;() 
          }
        );
      &lt;span style="color: green"&gt;// quick copy it
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyObject &lt;/span&gt;&lt;span style="color: #400080"&gt;mobj2 &lt;/span&gt;= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyObject&lt;/span&gt;(&lt;span style="color: #400080"&gt;mobj1&lt;/span&gt;);
      &lt;span style="color: green"&gt;// add a lot more items
      &lt;/span&gt;&lt;span style="color: blue"&gt;for &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;&lt;span style="color: #400080"&gt;i &lt;/span&gt;= 8; &lt;span style="color: #400080"&gt;i &lt;/span&gt;&amp;lt; 712324; ++&lt;span style="color: #400080"&gt;i&lt;/span&gt;)
        &lt;span style="color: #400080"&gt;mobj2&lt;/span&gt;.&lt;span style="color: #400080"&gt;kc&lt;/span&gt;.&lt;span style="color: #400080"&gt;Add&lt;/span&gt;(
          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CFoo&lt;/span&gt;() { 
            &lt;span style="color: #400080"&gt;Key &lt;/span&gt;= &lt;span style="color: #400080"&gt;i&lt;/span&gt;, &lt;span style="color: #400080"&gt;Name &lt;/span&gt;= &lt;span style="color: #400080"&gt;i&lt;/span&gt;.&lt;span style="color: #400080"&gt;ToString&lt;/span&gt;() 
          }
        );
      &lt;span style="color: green"&gt;// quick copy this one.
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyObject &lt;/span&gt;&lt;span style="color: #400080"&gt;mobj3 &lt;/span&gt;= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyObject&lt;/span&gt;(&lt;span style="color: #400080"&gt;mobj2&lt;/span&gt;);
      &lt;span style="color: green"&gt;// by looking in debugger, you can see that the first 
      // list has 7 items, the second has 712331 and so does 
      // the 3rd the first 7 items of all objects are the 
      // same the last 712324 items of the last 2 objects 
      // are the same!  hey this works!
    &lt;/span&gt;}
  }

  &lt;span style="color: green"&gt;/* ---------------------------------------------------------
   * CollectionTools contains three functions that can be
   * used to copy a list, a dictionary, or a keyedcollection
   * ------------------------------------------------------ */
  &lt;/span&gt;&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CollectionTools &lt;/span&gt;{

    &lt;span style="color: blue"&gt;public unsafe static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;KeyedCollection&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt; 
     &lt;span style="color: #400080"&gt;CopyKeyedCollection&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt;(
     &lt;span style="color: #2b91af"&gt;KeyedCollection&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt; &lt;span style="color: #400080"&gt;src&lt;/span&gt;, 
     &lt;span style="color: #2b91af"&gt;KeyedCollection&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt; &lt;span style="color: #400080"&gt;dst&lt;/span&gt;) {

      &lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;osrc &lt;/span&gt;= &lt;span style="color: #400080"&gt;src&lt;/span&gt;;
      &lt;span style="color: green"&gt;// TKeyedCollection* is pointer to a structure 
      // that is a template for the 
      // instance variables of A KeyedCollection&amp;lt;TKey, TValue&amp;gt;
      // What is going on here is that src is copied to osrc, 
      // which is on the stack exactly 4 bytes after psrc. 
      // hence the (int*)&amp;amp;psrc + 1.  osrc is a pointer to
      // the object on the heap, so we copy *osrc to &amp;amp;psrc
      // which causes our structure to overlay the class
      // if you change the order of these variables on the 
      // stack, then this trick wont work.
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TKeyedCollection&lt;/span&gt;* &lt;span style="color: #400080"&gt;psrc &lt;/span&gt;= 
       (&lt;span style="color: #2b91af"&gt;TKeyedCollection&lt;/span&gt;*)(*((&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;psrc &lt;/span&gt;+ 1));  
      &lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;odst &lt;/span&gt;= &lt;span style="color: #400080"&gt;dst&lt;/span&gt;;
      &lt;span style="color: #2b91af"&gt;TKeyedCollection&lt;/span&gt;* &lt;span style="color: #400080"&gt;pdst &lt;/span&gt;= 
       (&lt;span style="color: #2b91af"&gt;TKeyedCollection&lt;/span&gt;*)(*((&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;pdst &lt;/span&gt;+ 1));
      &lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;srcObj &lt;/span&gt;= &lt;span style="color: blue"&gt;null&lt;/span&gt;;  &lt;span style="color: green"&gt;// i use i[2] to change this
      &lt;/span&gt;&lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;dstObj &lt;/span&gt;= &lt;span style="color: blue"&gt;null&lt;/span&gt;;  &lt;span style="color: green"&gt;// i use i[1] to change this
      &lt;/span&gt;&lt;span style="color: blue"&gt;int&lt;/span&gt;* &lt;span style="color: #400080"&gt;i &lt;/span&gt;= (&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;i&lt;/span&gt;;  &lt;span style="color: green"&gt;// helps me find the stack

      // copy the internal list, by calling CopyList
      &lt;/span&gt;&lt;span style="color: #400080"&gt;i&lt;/span&gt;[2] = (&lt;span style="color: blue"&gt;int&lt;/span&gt;)&lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_01_items&lt;/span&gt;;  
      &lt;span style="color: #400080"&gt;dstObj &lt;/span&gt;= &lt;span style="color: #400080"&gt;CopyList&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt;(&lt;span style="color: #400080"&gt;srcObj &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt;);
      &lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_01_items &lt;/span&gt;= (&lt;span style="color: blue"&gt;uint&lt;/span&gt;)&lt;span style="color: #400080"&gt;i&lt;/span&gt;[1];

      &lt;span style="color: green"&gt;// copy the internal dictionary.  There is only a
      // dictionary once an internal count threshold has
      // been reached.  Sometimes there is no dictionary
      &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_04_dict &lt;/span&gt;!= 0) {
        &lt;span style="color: green"&gt;// copy the internal dictionary by calling CopyDict
        &lt;/span&gt;&lt;span style="color: #400080"&gt;i&lt;/span&gt;[2] = (&lt;span style="color: blue"&gt;int&lt;/span&gt;)&lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_04_dict&lt;/span&gt;;
        &lt;span style="color: #400080"&gt;dstObj &lt;/span&gt;= &lt;span style="color: #400080"&gt;CopyDict&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt;(
         &lt;span style="color: #400080"&gt;srcObj &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt;);
        &lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_04_dict &lt;/span&gt;= (&lt;span style="color: blue"&gt;uint&lt;/span&gt;)&lt;span style="color: #400080"&gt;i&lt;/span&gt;[1];
      }

      &lt;span style="color: green"&gt;// copy the rest of the values 
      &lt;/span&gt;&lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_03_comparer &lt;/span&gt;= &lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_03_comparer&lt;/span&gt;;
      &lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_05_keyCount &lt;/span&gt;= &lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_05_keyCount&lt;/span&gt;;
      &lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_06_threshold &lt;/span&gt;= &lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_06_threshold&lt;/span&gt;;
      &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #400080"&gt;dst&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public unsafe static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt; &lt;span style="color: #400080"&gt;CopyList&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt;(
     &lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt; &lt;span style="color: #400080"&gt;src&lt;/span&gt;) {

      &lt;span style="color: green"&gt;// see previous comments for notes about these local
      // variables
      &lt;/span&gt;&lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;osrc &lt;/span&gt;= &lt;span style="color: #400080"&gt;src&lt;/span&gt;;
      &lt;span style="color: #2b91af"&gt;TList&lt;/span&gt;* &lt;span style="color: #400080"&gt;psrc &lt;/span&gt;= (&lt;span style="color: #2b91af"&gt;TList&lt;/span&gt;*)(*((&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;psrc &lt;/span&gt;+ 1));  
      &lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;srcArray &lt;/span&gt;= &lt;span style="color: blue"&gt;null&lt;/span&gt;;
      &lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;dstArray &lt;/span&gt;= &lt;span style="color: blue"&gt;null&lt;/span&gt;;
      &lt;span style="color: blue"&gt;int&lt;/span&gt;* &lt;span style="color: #400080"&gt;i &lt;/span&gt;= (&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;i&lt;/span&gt;;  

      &lt;span style="color: green"&gt;// a list has an array of items
      
      // I need c# to consider _01_items as an object,
      // so I use my handy dandy stack munger, i, to
      // set the srcArray and dstArray
      &lt;/span&gt;&lt;span style="color: #400080"&gt;i&lt;/span&gt;[2] = (&lt;span style="color: blue"&gt;int&lt;/span&gt;)&lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_01_items&lt;/span&gt;;  
      &lt;span style="color: green"&gt;// its easy to create an empty array of the right
      // size using one of the List&amp;lt;&amp;gt; constructors
      &lt;/span&gt;&lt;span style="color: blue"&gt;int &lt;/span&gt;&lt;span style="color: #400080"&gt;capacity &lt;/span&gt;= (&lt;span style="color: #400080"&gt;srcArray &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;).&lt;span style="color: #400080"&gt;Length&lt;/span&gt;;
      &lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt; &lt;span style="color: #400080"&gt;dst &lt;/span&gt;= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt;(&lt;span style="color: #400080"&gt;capacity&lt;/span&gt;);
      &lt;span style="color: green"&gt;// overlay a hack structure on the list we just
      // created, so we can copy stuff to it
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TList&lt;/span&gt;* &lt;span style="color: #400080"&gt;pdst &lt;/span&gt;= (&lt;span style="color: #2b91af"&gt;TList&lt;/span&gt;*)(*((&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;pdst &lt;/span&gt;+ 1));
      &lt;span style="color: green"&gt;// now setup dstArray
      &lt;/span&gt;&lt;span style="color: #400080"&gt;i&lt;/span&gt;[1] = (&lt;span style="color: blue"&gt;int&lt;/span&gt;)&lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_01_items&lt;/span&gt;; 
      &lt;span style="color: green"&gt;// now that srcArray and dstArray are set, we can  
      // let C# do the copying for us.  This saves us 
      // having to determine the size of each element
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;.&lt;span style="color: #400080"&gt;Copy&lt;/span&gt;(&lt;span style="color: #400080"&gt;srcArray &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;, &lt;span style="color: #400080"&gt;dstArray &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;, 
       &lt;span style="color: #400080"&gt;capacity&lt;/span&gt;);

      &lt;span style="color: green"&gt;// set the size, which is the # of used elements 
      // of the list
      &lt;/span&gt;&lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_03_size &lt;/span&gt;= &lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_03_size&lt;/span&gt;;

      &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #400080"&gt;dst&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public unsafe static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt; 
     &lt;span style="color: #400080"&gt;CopyDict&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt;(
     &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt; &lt;span style="color: #400080"&gt;src&lt;/span&gt;) {

      &lt;span style="color: green"&gt;// see previous comments for notes about these local
      // variables
      &lt;/span&gt;&lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;osrc &lt;/span&gt;= &lt;span style="color: #400080"&gt;src&lt;/span&gt;;
      &lt;span style="color: #2b91af"&gt;TDictionary&lt;/span&gt;* &lt;span style="color: #400080"&gt;psrc &lt;/span&gt;= 
       (&lt;span style="color: #2b91af"&gt;TDictionary&lt;/span&gt;*)(*((&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;psrc &lt;/span&gt;+ 1)); 
      &lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;srcArray &lt;/span&gt;= &lt;span style="color: blue"&gt;null&lt;/span&gt;;
      &lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;dstArray &lt;/span&gt;= &lt;span style="color: blue"&gt;null&lt;/span&gt;;
      &lt;span style="color: blue"&gt;int&lt;/span&gt;* &lt;span style="color: #400080"&gt;i &lt;/span&gt;= (&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;i&lt;/span&gt;;  &lt;span style="color: green"&gt;// helps me find the stack

      // a dictionary has a hash table called buckets

      // I need c# to consider _01_buckets as an object,
      // so I use my handy dandy stack munger, i, to
      // set the srcArray and dstArray
      &lt;/span&gt;&lt;span style="color: #400080"&gt;i&lt;/span&gt;[2] = (&lt;span style="color: blue"&gt;int&lt;/span&gt;)&lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_01_buckets&lt;/span&gt;;
      &lt;span style="color: green"&gt;// create a dictionary the same size as the src 
      // dictionary
      &lt;/span&gt;&lt;span style="color: blue"&gt;int &lt;/span&gt;&lt;span style="color: #400080"&gt;capacity &lt;/span&gt;= (&lt;span style="color: #400080"&gt;srcArray &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;).&lt;span style="color: #400080"&gt;Length&lt;/span&gt;;
      &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt; &lt;span style="color: #400080"&gt;dst &lt;/span&gt;=
       &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #400080"&gt;TKey&lt;/span&gt;, &lt;span style="color: #400080"&gt;TValue&lt;/span&gt;&amp;gt;(&lt;span style="color: #400080"&gt;capacity&lt;/span&gt;);
      &lt;span style="color: green"&gt;// overlay the hack structure
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TDictionary&lt;/span&gt;* &lt;span style="color: #400080"&gt;pdst &lt;/span&gt;= 
       (&lt;span style="color: #2b91af"&gt;TDictionary&lt;/span&gt;*)(*((&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;pdst &lt;/span&gt;+ 1));
      &lt;span style="color: green"&gt;// now setup dstArray
      &lt;/span&gt;&lt;span style="color: #400080"&gt;i&lt;/span&gt;[1] = (&lt;span style="color: blue"&gt;int&lt;/span&gt;)&lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_01_buckets&lt;/span&gt;;
      &lt;span style="color: green"&gt;// now that srcArray and dstArray are set, we can  
      // let C# do the copying for us.  This saves us 
      // having to determine the size of each element
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;.&lt;span style="color: #400080"&gt;Copy&lt;/span&gt;(&lt;span style="color: #400080"&gt;srcArray &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;, &lt;span style="color: #400080"&gt;dstArray &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;,
       &lt;span style="color: #400080"&gt;capacity&lt;/span&gt;);

      &lt;span style="color: green"&gt;// a dictionary also has keeps the data stored 
      // in an array
      &lt;/span&gt;&lt;span style="color: #400080"&gt;i&lt;/span&gt;[2] = (&lt;span style="color: blue"&gt;int&lt;/span&gt;)&lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_02_entries&lt;/span&gt;;
      &lt;span style="color: #400080"&gt;i&lt;/span&gt;[1] = (&lt;span style="color: blue"&gt;int&lt;/span&gt;)&lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_02_entries&lt;/span&gt;;
      &lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;.&lt;span style="color: #400080"&gt;Copy&lt;/span&gt;(&lt;span style="color: #400080"&gt;srcArray &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;, &lt;span style="color: #400080"&gt;dstArray &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Array&lt;/span&gt;, 
       &lt;span style="color: #400080"&gt;capacity&lt;/span&gt;);

      &lt;span style="color: green"&gt;// copy the remaining simple variables
      &lt;/span&gt;&lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_03_comparer &lt;/span&gt;= &lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_03_comparer&lt;/span&gt;;
      &lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_04_m_siInfo &lt;/span&gt;= &lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_04_m_siInfo&lt;/span&gt;;
      &lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_08_count &lt;/span&gt;= &lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_08_count&lt;/span&gt;;
      &lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_10_freeList &lt;/span&gt;= &lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_10_freeList&lt;/span&gt;;
      &lt;span style="color: #400080"&gt;pdst&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_11_freeCount &lt;/span&gt;= &lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_11_freeCount&lt;/span&gt;;

      &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #400080"&gt;dst&lt;/span&gt;;
    }
    &lt;span style="color: green"&gt;/* -------------------------------------------------------
     * These are the structs that map onto the classes which
     * I use to access the private member variables
     * Items marked with * I determined needed to be copied
     * -----------------------------------------------------*/
 
    &lt;/span&gt;&lt;span style="color: blue"&gt;struct &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TKeyedCollection &lt;/span&gt;{
      &lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_00_MethodInfo&lt;/span&gt;;   &lt;span style="color: green"&gt;//
      // Collection
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_01_items&lt;/span&gt;;      &lt;span style="color: green"&gt;// * IList&amp;lt;T&amp;gt;
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_02_syncRoot&lt;/span&gt;;   &lt;span style="color: green"&gt;//   object
      // KeyedCollection
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_03_comparer&lt;/span&gt;;   &lt;span style="color: green"&gt;//   IEqualityComparer&amp;lt;TKey&amp;gt; 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_04_dict&lt;/span&gt;;       &lt;span style="color: green"&gt;// * Dictionary&amp;lt;TKey, TItem&amp;gt; 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public int &lt;/span&gt;&lt;span style="color: #400080"&gt;_05_keyCount&lt;/span&gt;;    &lt;span style="color: green"&gt;// *
      &lt;/span&gt;&lt;span style="color: blue"&gt;public int &lt;/span&gt;&lt;span style="color: #400080"&gt;_06_threshold&lt;/span&gt;;   &lt;span style="color: green"&gt;// *
    &lt;/span&gt;}

    &lt;span style="color: blue"&gt;struct &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TList &lt;/span&gt;{
      &lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_00_MethodInfo&lt;/span&gt;; &lt;span style="color: green"&gt;//
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_01_items&lt;/span&gt;;      &lt;span style="color: green"&gt;// * T[] 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_02_syncRoot&lt;/span&gt;;   &lt;span style="color: green"&gt;//   object
      &lt;/span&gt;&lt;span style="color: blue"&gt;public int &lt;/span&gt;&lt;span style="color: #400080"&gt;_03_size&lt;/span&gt;;        &lt;span style="color: green"&gt;// *
      &lt;/span&gt;&lt;span style="color: blue"&gt;public int &lt;/span&gt;&lt;span style="color: #400080"&gt;_04_version&lt;/span&gt;;     &lt;span style="color: green"&gt;//
    &lt;/span&gt;}

    &lt;span style="color: blue"&gt;struct &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TDictionary &lt;/span&gt;{
      &lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_00_MethodInfo&lt;/span&gt;; &lt;span style="color: green"&gt;//
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_01_buckets&lt;/span&gt;;    &lt;span style="color: green"&gt;// * int[] 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_02_entries&lt;/span&gt;;    &lt;span style="color: green"&gt;// * Entry&amp;lt;TKey, TValue&amp;gt;[] 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_03_comparer&lt;/span&gt;;   &lt;span style="color: green"&gt;//   IEqualityComparer&amp;lt;TKey&amp;gt; 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_04_m_siInfo&lt;/span&gt;;   &lt;span style="color: green"&gt;//   SerializationInfo
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_05__syncRoot&lt;/span&gt;;  &lt;span style="color: green"&gt;//   object 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_06_keys&lt;/span&gt;;       &lt;span style="color: green"&gt;//   KeyCollection&amp;lt;,&amp;gt; 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public uint &lt;/span&gt;&lt;span style="color: #400080"&gt;_07_values&lt;/span&gt;;     &lt;span style="color: green"&gt;//   ValueCollection&amp;lt;,&amp;gt; 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public int &lt;/span&gt;&lt;span style="color: #400080"&gt;_08_count&lt;/span&gt;;       &lt;span style="color: green"&gt;// *
      &lt;/span&gt;&lt;span style="color: blue"&gt;public int &lt;/span&gt;&lt;span style="color: #400080"&gt;_09_version&lt;/span&gt;;
      &lt;span style="color: blue"&gt;public int &lt;/span&gt;&lt;span style="color: #400080"&gt;_10_freeList&lt;/span&gt;;    &lt;span style="color: green"&gt;// * 
      &lt;/span&gt;&lt;span style="color: blue"&gt;public int &lt;/span&gt;&lt;span style="color: #400080"&gt;_11_freeCount&lt;/span&gt;;   &lt;span style="color: green"&gt;// *
    &lt;/span&gt;}

  }


}&lt;/pre&gt;

&lt;p&gt;This construct, “&lt;span style="color: blue"&gt;int&lt;/span&gt;* &lt;span style="color: #400080"&gt;i &lt;/span&gt;= (&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;i&lt;/span&gt;”, sets the pointer i (nice name for a pointer…) to point to itself.&amp;#160; “i” is located on the stack, so now I have a pointer to a spot on the stack.&amp;#160; Now if we use “i” as an array, we can access variables on the stack in ways that keep C# from complaining about casting.&amp;#160; You don’t get a “cannot cast a managed object to a void *” (or vice versa) error when you set an object this way: “&lt;span style="color: #400080"&gt;i&lt;/span&gt;[2] = (&lt;span style="color: blue"&gt;int&lt;/span&gt;)&lt;span style="color: #400080"&gt;psrc&lt;/span&gt;-&amp;gt;&lt;span style="color: #400080"&gt;_01_items&lt;/span&gt;”&amp;#160; “i[2]” means the int located 2 ints above “i” in the stack.&amp;#160; I assume everyone knows ints are 4 bytes.&amp;#160; I chose ints because almost everything I am messing with is a managed object, which is really a pointer, which is 4 bytes long.&amp;#160; Now if you look at the variables declared on the stack in front of “i”, just count up 2 ints.&amp;#160; This is the variable that is being set by “i[2]”.&amp;#160; Once I get better at this blogging thing I will draw a picture.&lt;/p&gt;

&lt;pre class="code"&gt;      &lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;srcObj &lt;/span&gt;= &lt;span style="color: blue"&gt;null&lt;/span&gt;;  &lt;span style="color: green"&gt;// i use i[2] to change this
      &lt;/span&gt;&lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;dstObj &lt;/span&gt;= &lt;span style="color: blue"&gt;null&lt;/span&gt;;  &lt;span style="color: green"&gt;// i use i[1] to change this
      &lt;/span&gt;&lt;span style="color: blue"&gt;int&lt;/span&gt;* &lt;span style="color: #400080"&gt;i &lt;/span&gt;= (&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;i&lt;/span&gt;;  &lt;span style="color: green"&gt;// helps me find the stack
&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The same sort of thing is going on here&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;object &lt;/span&gt;&lt;span style="color: #400080"&gt;osrc &lt;/span&gt;= &lt;span style="color: #400080"&gt;src&lt;/span&gt;;
&lt;span style="color: #2b91af"&gt;TDictionary&lt;/span&gt;* &lt;span style="color: #400080"&gt;psrc &lt;/span&gt;= 
 (&lt;span style="color: #2b91af"&gt;TDictionary&lt;/span&gt;*)(*((&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;psrc &lt;/span&gt;+ 1)); &lt;/pre&gt;

&lt;p&gt;&amp;amp;psrc is on the stack, 4 bytes before it, “(int*)&amp;amp;&lt;span style="color: #400080"&gt;psrc &lt;/span&gt;+ 1”, is osrc.&amp;#160; The value of osrc, “*((&lt;span style="color: blue"&gt;int&lt;/span&gt;*)&amp;amp;&lt;span style="color: #400080"&gt;psrc &lt;/span&gt;+ 1)”, is the address of src in the heap.&amp;#160; Cast that as a TDictionary* and you have just overlaid a structure on a class.&lt;/p&gt;

&lt;p&gt;The way I figured out what to copy was by using the RedGate .Net Relfector.&amp;#160; I just looked at the code for all the aforementioned collections to figure out what the instance variables were and then what was important and needed to be copied.&lt;/p&gt;

&lt;p&gt;Unfortunately, the order of the instance variables in RedGate’s Reflector and in Type.GetFields() is not the order of the instance variables in memory.&amp;#160; To figure this out, I had to look at the objects in the memory dump of visual studio.&amp;#160; Techniques to figure out what random bytes in the heap actually are is a good topic for a future article.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7162964-9196888918933960230?l=buiba.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://buiba.blogspot.com/feeds/9196888918933960230/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7162964&amp;postID=9196888918933960230' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/9196888918933960230'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/9196888918933960230'/><link rel='alternate' type='text/html' href='http://buiba.blogspot.com/2009/06/copy-c-keyedcollection-list-or.html' title='High Performance Method to Copy C# KeyedCollection&amp;lt;,&amp;gt;, List&amp;lt;&amp;gt;, and Dictionary&amp;lt;,&amp;gt;'/><author><name>johnnycrash</name><uri>http://www.blogger.com/profile/00685855809394991386</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7162964.post-7916185179330117370</id><published>2009-06-17T01:43:00.001-07:00</published><updated>2009-06-17T04:24:41.440-07:00</updated><title type='text'>Using the WIN32 API Functions CreateFile, ReadFile, WriteFile, SetFilePointer from C#</title><content type='html'>&lt;p&gt;What if for some reason you need to use the WIN32 API to read and write files?  I know FileStream can do a lot of what the WIN32 API can do, but this is a "what if".... a hypothetical situation, ok!  (don't think for one second I did this because I thought I couldn't seek to a spot in a file and write some bytes...ok...not for one second did I not know about FileStream.Seek)
&lt;/p&gt;  &lt;p&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;WinApiFile &lt;/span&gt;is my class that wraps the basic functionality of the 4 WIN32 API functions.  Here is the class and a sample console app that uses the class to 1) read a file and close it and then 2) re-open the file and write a couple bytes in the middle of it.  Not included is a little text file that needs to be located where the compiled executable is created.  I just add a text file to the project and tell visual studio to copy it to the destination directory every time I run the app.&lt;/p&gt;  &lt;p&gt;I got a little bit of the code, although its vastly changed now, from the MSDN website.&lt;/p&gt; &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;using &lt;/span&gt;System;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;Microsoft.Win32.SafeHandles;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;System.Runtime.InteropServices;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;System.ComponentModel;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;System.Windows.Forms;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Path &lt;/span&gt;= System.IO.&lt;span style="color: rgb(43, 145, 175);"&gt;Path&lt;/span&gt;;

&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Program &lt;/span&gt;{

&lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main() {

  &lt;span style="color:blue;"&gt;string &lt;/span&gt;sTestFile = &lt;span style="color: rgb(43, 145, 175);"&gt;Path&lt;/span&gt;.Combine(&lt;span style="color: rgb(43, 145, 175);"&gt;Path&lt;/span&gt;.GetDirectoryName(
   &lt;span style="color: rgb(43, 145, 175);"&gt;Application&lt;/span&gt;.ExecutablePath), &lt;span style="color: rgb(163, 21, 21);"&gt;"Test.txt"&lt;/span&gt;);

  &lt;span style="color:green;"&gt;// test reading a file
  &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;WinApiFile &lt;/span&gt;File = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;WinApiFile&lt;/span&gt;(sTestFile,
   &lt;span style="color: rgb(43, 145, 175);"&gt;WinApiFile&lt;/span&gt;.&lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess&lt;/span&gt;.GENERIC_READ);
  &lt;span style="color:blue;"&gt;byte&lt;/span&gt;[] aBuffer = &lt;span style="color:blue;"&gt;new byte&lt;/span&gt;[1000];
  &lt;span style="color:blue;"&gt;uint &lt;/span&gt;cbRead = File.Read(aBuffer, 1000);
  File.Close();

  &lt;span style="color:green;"&gt;// Test writing the file
  &lt;/span&gt;File.Open(&lt;span style="color: rgb(43, 145, 175);"&gt;WinApiFile&lt;/span&gt;.&lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess&lt;/span&gt;.GENERIC_WRITE);
  &lt;span style="color:green;"&gt;// write the time to a 10 byte offset in the file
  // conver the date time to byte array
  &lt;/span&gt;&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0;
  &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;ch &lt;span style="color:blue;"&gt;in &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;DateTime&lt;/span&gt;.Now.ToString())
    aBuffer[i++] = (&lt;span style="color:blue;"&gt;byte&lt;/span&gt;)ch;
  &lt;span style="color:green;"&gt;// now write it out
  &lt;/span&gt;File.MoveFilePointer(10);  &lt;span style="color:green;"&gt;// 10 byte offset
  &lt;/span&gt;File.Write(aBuffer, (&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i);  &lt;span style="color:green;"&gt;// write the time
  &lt;/span&gt;File.Dispose();
}
}

&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;WinApiFile &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;IDisposable &lt;/span&gt;{

&lt;span style="color:green;"&gt;/* ---------------------------------------------------------
 * private members
 * ------------------------------------------------------ */
&lt;/span&gt;&lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;_hFile = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;
&lt;span style="color:blue;"&gt;private string &lt;/span&gt;_sFileName = &lt;span style="color: rgb(163, 21, 21);"&gt;""&lt;/span&gt;;
&lt;span style="color:blue;"&gt;private bool &lt;/span&gt;_fDisposed;

&lt;span style="color:green;"&gt;/* ---------------------------------------------------------
 * properties
 * ------------------------------------------------------ */
&lt;/span&gt;&lt;span style="color:blue;"&gt;public bool &lt;/span&gt;IsOpen { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;(_hFile != &lt;span style="color:blue;"&gt;null&lt;/span&gt;); } }
&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;Handle { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;_hFile; } }
&lt;span style="color:blue;"&gt;public string &lt;/span&gt;FileName {
  &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;_sFileName; }
  &lt;span style="color:blue;"&gt;set &lt;/span&gt;{
    _sFileName = (&lt;span style="color:blue;"&gt;value &lt;/span&gt;?? &lt;span style="color: rgb(163, 21, 21);"&gt;""&lt;/span&gt;).Trim();
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_sFileName.Length == 0)
      CloseHandle(_hFile);
  }
}
&lt;span style="color:blue;"&gt;public int &lt;/span&gt;FileLength {
  &lt;span style="color:blue;"&gt;get &lt;/span&gt;{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;(_hFile != &lt;span style="color:blue;"&gt;null&lt;/span&gt;) ? (&lt;span style="color:blue;"&gt;int&lt;/span&gt;)GetFileSize(_hFile,
     &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr&lt;/span&gt;.Zero) : 0;
  }
  &lt;span style="color:blue;"&gt;set &lt;/span&gt;{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_hFile == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
      &lt;span style="color:blue;"&gt;return&lt;/span&gt;;
    MoveFilePointer(&lt;span style="color:blue;"&gt;value&lt;/span&gt;, &lt;span style="color: rgb(43, 145, 175);"&gt;MoveMethod&lt;/span&gt;.FILE_BEGIN);
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!SetEndOfFile(_hFile))
      ThrowLastWin32Err();
  }
}

&lt;span style="color:green;"&gt;/* ---------------------------------------------------------
 * Constructors
 * ------------------------------------------------------ */

&lt;/span&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;WinApiFile(&lt;span style="color:blue;"&gt;string &lt;/span&gt;sFileName,
 &lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess &lt;/span&gt;fDesiredAccess) {
  FileName = sFileName;
  Open(fDesiredAccess);
}
&lt;span style="color:blue;"&gt;public &lt;/span&gt;WinApiFile(&lt;span style="color:blue;"&gt;string &lt;/span&gt;sFileName,
 &lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess &lt;/span&gt;fDesiredAccess,
 &lt;span style="color: rgb(43, 145, 175);"&gt;CreationDisposition &lt;/span&gt;fCreationDisposition) {
  FileName = sFileName;
  Open(fDesiredAccess, fCreationDisposition);
}

&lt;span style="color:green;"&gt;/* ---------------------------------------------------------
 * Open/Close
 * ------------------------------------------------------ */

&lt;/span&gt;&lt;span style="color:blue;"&gt;public void &lt;/span&gt;Open(
 &lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess &lt;/span&gt;fDesiredAccess) {
  Open(fDesiredAccess, &lt;span style="color: rgb(43, 145, 175);"&gt;CreationDisposition&lt;/span&gt;.OPEN_EXISTING);
}

&lt;span style="color:blue;"&gt;public void &lt;/span&gt;Open(
 &lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess &lt;/span&gt;fDesiredAccess,
 &lt;span style="color: rgb(43, 145, 175);"&gt;CreationDisposition &lt;/span&gt;fCreationDisposition) {
  &lt;span style="color: rgb(43, 145, 175);"&gt;ShareMode &lt;/span&gt;fShareMode;
  &lt;span style="color:blue;"&gt;if &lt;/span&gt;(fDesiredAccess == &lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess&lt;/span&gt;.GENERIC_READ) {
    fShareMode = &lt;span style="color: rgb(43, 145, 175);"&gt;ShareMode&lt;/span&gt;.FILE_SHARE_READ;
  } &lt;span style="color:blue;"&gt;else &lt;/span&gt;{
    fShareMode = &lt;span style="color: rgb(43, 145, 175);"&gt;ShareMode&lt;/span&gt;.FILE_SHARE_NONE;
  }
  Open(fDesiredAccess, fShareMode, fCreationDisposition, 0);
}

&lt;span style="color:blue;"&gt;public void &lt;/span&gt;Open(
 &lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess &lt;/span&gt;fDesiredAccess,
 &lt;span style="color: rgb(43, 145, 175);"&gt;ShareMode &lt;/span&gt;fShareMode,
 &lt;span style="color: rgb(43, 145, 175);"&gt;CreationDisposition &lt;/span&gt;fCreationDisposition,
 &lt;span style="color: rgb(43, 145, 175);"&gt;FlagsAndAttributes &lt;/span&gt;fFlagsAndAttributes) {

  &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_sFileName.Length == 0)
    &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: rgb(163, 21, 21);"&gt;"FileName"&lt;/span&gt;);
  _hFile = CreateFile(_sFileName, fDesiredAccess, fShareMode,
   &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr&lt;/span&gt;.Zero, fCreationDisposition, fFlagsAndAttributes,
   &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr&lt;/span&gt;.Zero);
  &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_hFile.IsInvalid) {
    _hFile = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;
    ThrowLastWin32Err();
  }
  _fDisposed = &lt;span style="color:blue;"&gt;false&lt;/span&gt;;

}

&lt;span style="color:blue;"&gt;public void &lt;/span&gt;Close() {
  &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_hFile == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
    &lt;span style="color:blue;"&gt;return&lt;/span&gt;;
  _hFile.Close();
  _hFile = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;
  _fDisposed = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;
}

&lt;span style="color:green;"&gt;/* ---------------------------------------------------------
 * Move file pointer
 * ------------------------------------------------------ */

&lt;/span&gt;&lt;span style="color:blue;"&gt;public void &lt;/span&gt;MoveFilePointer(&lt;span style="color:blue;"&gt;int &lt;/span&gt;cbToMove) {
  MoveFilePointer(cbToMove, &lt;span style="color: rgb(43, 145, 175);"&gt;MoveMethod&lt;/span&gt;.FILE_CURRENT);
}

&lt;span style="color:blue;"&gt;public void &lt;/span&gt;MoveFilePointer(&lt;span style="color:blue;"&gt;int &lt;/span&gt;cbToMove,
 &lt;span style="color: rgb(43, 145, 175);"&gt;MoveMethod &lt;/span&gt;fMoveMethod) {
  &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_hFile != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(SetFilePointer(_hFile, cbToMove, &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr&lt;/span&gt;.Zero,
     fMoveMethod) == INVALID_SET_FILE_POINTER)
      ThrowLastWin32Err();
}

&lt;span style="color:blue;"&gt;public int &lt;/span&gt;FilePointer {
  &lt;span style="color:blue;"&gt;get &lt;/span&gt;{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;(_hFile != &lt;span style="color:blue;"&gt;null&lt;/span&gt;) ? (&lt;span style="color:blue;"&gt;int&lt;/span&gt;)SetFilePointer(_hFile, 0,
     &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr&lt;/span&gt;.Zero, &lt;span style="color: rgb(43, 145, 175);"&gt;MoveMethod&lt;/span&gt;.FILE_CURRENT) : 0;
  }
  &lt;span style="color:blue;"&gt;set &lt;/span&gt;{
    MoveFilePointer(&lt;span style="color:blue;"&gt;value&lt;/span&gt;);
  }
}

&lt;span style="color:green;"&gt;/* ---------------------------------------------------------
 * Read and Write
 * ------------------------------------------------------ */

&lt;/span&gt;&lt;span style="color:blue;"&gt;public uint &lt;/span&gt;Read(&lt;span style="color:blue;"&gt;byte&lt;/span&gt;[] buffer, &lt;span style="color:blue;"&gt;uint &lt;/span&gt;cbToRead) {
  &lt;span style="color:green;"&gt;// returns bytes read
  &lt;/span&gt;&lt;span style="color:blue;"&gt;uint &lt;/span&gt;cbThatWereRead = 0;
  &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!ReadFile(_hFile, buffer, cbToRead,
   &lt;span style="color:blue;"&gt;ref &lt;/span&gt;cbThatWereRead, &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr&lt;/span&gt;.Zero))
    ThrowLastWin32Err();
  &lt;span style="color:blue;"&gt;return &lt;/span&gt;cbThatWereRead;
}

&lt;span style="color:blue;"&gt;public uint &lt;/span&gt;Write(&lt;span style="color:blue;"&gt;byte&lt;/span&gt;[] buffer, &lt;span style="color:blue;"&gt;uint &lt;/span&gt;cbToWrite) {
  &lt;span style="color:green;"&gt;// returns bytes read
  &lt;/span&gt;&lt;span style="color:blue;"&gt;uint &lt;/span&gt;cbThatWereWritten = 0;
  &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!WriteFile(_hFile, buffer, cbToWrite,
   &lt;span style="color:blue;"&gt;ref &lt;/span&gt;cbThatWereWritten, &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr&lt;/span&gt;.Zero))
    ThrowLastWin32Err();
  &lt;span style="color:blue;"&gt;return &lt;/span&gt;cbThatWereWritten;
}

&lt;span style="color:green;"&gt;/* ---------------------------------------------------------
 * IDisposable Interface
 * ------------------------------------------------------ */
&lt;/span&gt;&lt;span style="color:blue;"&gt;public void &lt;/span&gt;Dispose() {
  Dispose(&lt;span style="color:blue;"&gt;true&lt;/span&gt;);
  &lt;span style="color: rgb(43, 145, 175);"&gt;GC&lt;/span&gt;.SuppressFinalize(&lt;span style="color:blue;"&gt;this&lt;/span&gt;);
}

&lt;span style="color:blue;"&gt;protected virtual void &lt;/span&gt;Dispose(&lt;span style="color:blue;"&gt;bool &lt;/span&gt;fDisposing) {
  &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!_fDisposed) {
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(fDisposing) {
      &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_hFile != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        _hFile.Dispose();
      _fDisposed = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;
    }
  }
}

~WinApiFile() {
  Dispose(&lt;span style="color:blue;"&gt;false&lt;/span&gt;);
}

&lt;span style="color:green;"&gt;/* ---------------------------------------------------------
 * WINAPI STUFF
 * ------------------------------------------------------ */

&lt;/span&gt;&lt;span style="color:blue;"&gt;private void &lt;/span&gt;ThrowLastWin32Err() {
  &lt;span style="color: rgb(43, 145, 175);"&gt;Marshal&lt;/span&gt;.ThrowExceptionForHR(
   &lt;span style="color: rgb(43, 145, 175);"&gt;Marshal&lt;/span&gt;.GetHRForLastWin32Error());
}

[&lt;span style="color: rgb(43, 145, 175);"&gt;Flags&lt;/span&gt;]
&lt;span style="color:blue;"&gt;public enum &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess &lt;/span&gt;: &lt;span style="color:blue;"&gt;uint &lt;/span&gt;{
  GENERIC_READ = 0x80000000,
  GENERIC_WRITE = 0x40000000
}
[&lt;span style="color: rgb(43, 145, 175);"&gt;Flags&lt;/span&gt;]
&lt;span style="color:blue;"&gt;public enum &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ShareMode &lt;/span&gt;: &lt;span style="color:blue;"&gt;uint &lt;/span&gt;{
  FILE_SHARE_NONE = 0x0,
  FILE_SHARE_READ = 0x1,
  FILE_SHARE_WRITE = 0x2,
  FILE_SHARE_DELETE = 0x4,

}
&lt;span style="color:blue;"&gt;public enum &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;MoveMethod &lt;/span&gt;: &lt;span style="color:blue;"&gt;uint &lt;/span&gt;{
  FILE_BEGIN = 0,
  FILE_CURRENT = 1,
  FILE_END = 2
}
&lt;span style="color:blue;"&gt;public enum &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;CreationDisposition &lt;/span&gt;: &lt;span style="color:blue;"&gt;uint &lt;/span&gt;{
  CREATE_NEW = 1,
  CREATE_ALWAYS = 2,
  OPEN_EXISTING = 3,
  OPEN_ALWAYS = 4,
  TRUNCATE_EXSTING = 5
}
[&lt;span style="color: rgb(43, 145, 175);"&gt;Flags&lt;/span&gt;]
&lt;span style="color:blue;"&gt;public enum &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;FlagsAndAttributes &lt;/span&gt;: &lt;span style="color:blue;"&gt;uint &lt;/span&gt;{
  FILE_ATTRIBUTES_ARCHIVE = 0x20,
  FILE_ATTRIBUTE_HIDDEN = 0x2,
  FILE_ATTRIBUTE_NORMAL = 0x80,
  FILE_ATTRIBUTE_OFFLINE = 0x1000,
  FILE_ATTRIBUTE_READONLY = 0x1,
  FILE_ATTRIBUTE_SYSTEM = 0x4,
  FILE_ATTRIBUTE_TEMPORARY = 0x100,
  FILE_FLAG_WRITE_THROUGH = 0x80000000,
  FILE_FLAG_OVERLAPPED = 0x40000000,
  FILE_FLAG_NO_BUFFERING = 0x20000000,
  FILE_FLAG_RANDOM_ACCESS = 0x10000000,
  FILE_FLAG_SEQUENTIAL_SCAN = 0x8000000,
  FILE_FLAG_DELETE_ON = 0x4000000,
  FILE_FLAG_POSIX_SEMANTICS = 0x1000000,
  FILE_FLAG_OPEN_REPARSE_POINT = 0x200000,
  FILE_FLAG_OPEN_NO_CALL = 0x100000
}

&lt;span style="color:blue;"&gt;public const uint &lt;/span&gt;INVALID_HANDLE_VALUE = 0xFFFFFFFF;
&lt;span style="color:blue;"&gt;public const uint &lt;/span&gt;INVALID_SET_FILE_POINTER = 0xFFFFFFFF;
&lt;span style="color:green;"&gt;// Use interop to call the CreateFile function.
// For more information about CreateFile,
// see the unmanaged MSDN reference library.
&lt;/span&gt;[&lt;span style="color: rgb(43, 145, 175);"&gt;DllImport&lt;/span&gt;(&lt;span style="color: rgb(163, 21, 21);"&gt;"kernel32.dll"&lt;/span&gt;, SetLastError = &lt;span style="color:blue;"&gt;true&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;internal static extern &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;CreateFile(
 &lt;span style="color:blue;"&gt;string &lt;/span&gt;lpFileName,
 &lt;span style="color: rgb(43, 145, 175);"&gt;DesiredAccess &lt;/span&gt;dwDesiredAccess,
 &lt;span style="color: rgb(43, 145, 175);"&gt;ShareMode &lt;/span&gt;dwShareMode,
 &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr &lt;/span&gt;lpSecurityAttributes,
 &lt;span style="color: rgb(43, 145, 175);"&gt;CreationDisposition &lt;/span&gt;dwCreationDisposition,
 &lt;span style="color: rgb(43, 145, 175);"&gt;FlagsAndAttributes &lt;/span&gt;dwFlagsAndAttributes,
 &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr &lt;/span&gt;hTemplateFile);

[&lt;span style="color: rgb(43, 145, 175);"&gt;DllImport&lt;/span&gt;(&lt;span style="color: rgb(163, 21, 21);"&gt;"kernel32"&lt;/span&gt;, SetLastError = &lt;span style="color:blue;"&gt;true&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;internal static extern &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Int32 &lt;/span&gt;CloseHandle(
 &lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;hObject);

[&lt;span style="color: rgb(43, 145, 175);"&gt;DllImport&lt;/span&gt;(&lt;span style="color: rgb(163, 21, 21);"&gt;"kernel32"&lt;/span&gt;, SetLastError = &lt;span style="color:blue;"&gt;true&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;internal static extern bool &lt;/span&gt;ReadFile(
 &lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;hFile,
 &lt;span style="color: rgb(43, 145, 175);"&gt;Byte&lt;/span&gt;[] aBuffer,
 &lt;span style="color: rgb(43, 145, 175);"&gt;UInt32 &lt;/span&gt;cbToRead,
 &lt;span style="color:blue;"&gt;ref &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;UInt32 &lt;/span&gt;cbThatWereRead,
 &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr &lt;/span&gt;pOverlapped);

[&lt;span style="color: rgb(43, 145, 175);"&gt;DllImport&lt;/span&gt;(&lt;span style="color: rgb(163, 21, 21);"&gt;"kernel32.dll"&lt;/span&gt;, SetLastError = &lt;span style="color:blue;"&gt;true&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;internal static extern bool &lt;/span&gt;WriteFile(
 &lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;hFile,
 &lt;span style="color: rgb(43, 145, 175);"&gt;Byte&lt;/span&gt;[] aBuffer,
 &lt;span style="color: rgb(43, 145, 175);"&gt;UInt32 &lt;/span&gt;cbToWrite,
 &lt;span style="color:blue;"&gt;ref &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;UInt32 &lt;/span&gt;cbThatWereWritten,
 &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr &lt;/span&gt;pOverlapped);

[&lt;span style="color: rgb(43, 145, 175);"&gt;DllImport&lt;/span&gt;(&lt;span style="color: rgb(163, 21, 21);"&gt;"kernel32.dll"&lt;/span&gt;, SetLastError = &lt;span style="color:blue;"&gt;true&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;internal static extern &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;UInt32 &lt;/span&gt;SetFilePointer(
 &lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;hFile,
 &lt;span style="color: rgb(43, 145, 175);"&gt;Int32 &lt;/span&gt;cbDistanceToMove,
 &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr &lt;/span&gt;pDistanceToMoveHigh,
 &lt;span style="color: rgb(43, 145, 175);"&gt;MoveMethod &lt;/span&gt;fMoveMethod);

[&lt;span style="color: rgb(43, 145, 175);"&gt;DllImport&lt;/span&gt;(&lt;span style="color: rgb(163, 21, 21);"&gt;"kernel32.dll"&lt;/span&gt;, SetLastError = &lt;span style="color:blue;"&gt;true&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;internal static extern bool &lt;/span&gt;SetEndOfFile(
 &lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;hFile);

[&lt;span style="color: rgb(43, 145, 175);"&gt;DllImport&lt;/span&gt;(&lt;span style="color: rgb(163, 21, 21);"&gt;"kernel32.dll"&lt;/span&gt;, SetLastError = &lt;span style="color:blue;"&gt;true&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;internal static extern &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;UInt32 &lt;/span&gt;GetFileSize(
 &lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;hFile,
 &lt;span style="color: rgb(43, 145, 175);"&gt;IntPtr &lt;/span&gt;pFileSizeHigh);

}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I use IntPtr wherever I intend to just pass a null.  When I used void *, I had to make the class unsafe.&lt;/p&gt;

&lt;p&gt;This construct “&lt;span style="color:blue;"&gt;enum &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SomeEnumName &lt;/span&gt;: &lt;span style="color:blue;"&gt;uint&lt;/span&gt;“ tells the compiler to make the enum a unsigned integer.&lt;/p&gt;

&lt;p&gt;The flags attribute, “[&lt;span style="color: rgb(43, 145, 175);"&gt;Flags&lt;/span&gt;]”, treats an enumeration like a bitfield.  The debugger prints, in clear English, all the names of the bits that have been set.&lt;/p&gt;

&lt;p&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SafeFileHandle &lt;/span&gt;is a wrapper class for a WinAPI file handle.  It will automatically dispose of the non managed handle upon garbage collection.  &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7162964-7916185179330117370?l=buiba.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://buiba.blogspot.com/feeds/7916185179330117370/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7162964&amp;postID=7916185179330117370' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/7916185179330117370'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/7916185179330117370'/><link rel='alternate' type='text/html' href='http://buiba.blogspot.com/2009/06/using-winapi-createfile-readfile.html' title='Using the WIN32 API Functions CreateFile, ReadFile, WriteFile, SetFilePointer from C#'/><author><name>johnnycrash</name><uri>http://www.blogger.com/profile/00685855809394991386</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7162964.post-6357134090851400591</id><published>2009-06-12T23:57:00.001-07:00</published><updated>2009-06-15T16:32:31.328-07:00</updated><title type='text'>Hacking a C# Covariant Generic Cast Solution</title><content type='html'>&lt;p&gt;Click &lt;a href="#gohere"&gt;here&lt;/a&gt; to skip the story of how I figured out the solution.&lt;/p&gt;  &lt;p&gt;So I get onto the phone for my first job interview and everything is going great until they hit me with this question.&amp;#160; Could the following pseudo code compile?&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;A &lt;/span&gt;{ } 
&lt;span style="color: blue"&gt;class&lt;/span&gt;&lt;span style="color: #2b91af"&gt; B&lt;/span&gt;: &lt;span style="color: #2b91af"&gt;A &lt;/span&gt;{ }
... 
&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt; a = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt;(); &lt;/pre&gt;

&lt;p&gt;I had no idea what that would do...I am a recovering VB developer who was a recovering C/C++ developer who was a recovering assembly developer, so details about C# generics are not my strong suit.&amp;#160; I knew it wouldn’t compile in C++, and I guessed that you could probably write code in List&amp;lt;&amp;gt; that run into problems, so I muttered something along the lines &amp;quot;uh I don't think it will compile… that doesn't look very good.&amp;quot;&amp;#160; The interviewer told me it would not compile and was an example of the lack of support for covariance/contravariance in generics in C#.&amp;#160; I didn’t get the job.&amp;#160; &lt;/p&gt;

&lt;p&gt;Covariance... contravariance... what the heck are they?&amp;#160; If you are like I was and don’t know what that word means, try &lt;a href="http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx"&gt;here&lt;/a&gt;&amp;#160; (courtesy of Eric Lippert.)&amp;#160; Read all the installments.&amp;#160; &lt;/p&gt;

&lt;p&gt;The gist is that this situation occurs enough that making it work would be handy.&amp;#160; Imagine if you had a grid that displayed a List&amp;lt;DataRow&amp;gt; and you had defined your own MyDataRow class that inherited from DataRow.&amp;#160; Wouldn’t you want to pass your List&amp;lt;MyDataRow&amp;gt; to the grid?&amp;#160; &lt;/p&gt;

&lt;p&gt;Back to the interview question.&amp;#160; Since class B inherits from class A at first glance it looks like it &lt;em&gt;should&lt;/em&gt; work.&amp;#160; A little research shows that it can work in some other languages.&amp;#160; A neat aside is that&amp;#160; C# supports covariant arrays :&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;[] a = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;[1000];&amp;#160; &lt;span style="color: green"&gt;// this compiles&lt;/span&gt; &lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Although, it is at the expense of runtime checking:&lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;[] aa = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;[1000];
aa[0] = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;();  &lt;span style="color: green"&gt;// looking good...&lt;/span&gt;
aa[1] = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;();  &lt;span style="color: green"&gt;// runtime ArrayTypeMismatchException&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Unfortunately the developers of C# decided to omit the support for covariance and contravariance with generic parameters for now.&amp;#160; Runtime checking is good enough reason for me (I like performance!&amp;#160; Faster please!)&amp;#160; In all fairness, C# isn’t meant to be the highest performing language in the world.&amp;#160; So why not do a quick runtime check on assignments and when passing parameters?&amp;#160; Why not allow inherited classes to pass the check?&amp;#160; The answer is they had more reasons than performance.&amp;#160; Consider this:&lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;B &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;A &lt;/span&gt;{
  &lt;span style="color: blue"&gt;int &lt;/span&gt;_SomeVar;  &lt;span style="color: green"&gt;// B is larger than A now...  
&lt;/span&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now B is larger than A.&amp;#160; If List&amp;lt;T&amp;gt; had a function that 1) created a new T and 2) added the new T to its list, you would need a runtime exception to prevent memory corruption even though B &lt;em&gt;is an inherited class&lt;/em&gt;.&amp;#160; &lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;p&gt;&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Extension &lt;/span&gt;{
  &lt;span style="color: green"&gt;// runtime exception or memory corruption… you pick!
  &lt;/span&gt;&lt;span style="color: blue"&gt;public static void&lt;/span&gt; AddNew&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt; list) &lt;br /&gt;   &lt;span style="color: blue"&gt;where &lt;/span&gt;T:&lt;span style="color: blue"&gt;new&lt;/span&gt;() {
    T item = &lt;span style="color: blue"&gt;new &lt;/span&gt;T();
    list.Add(item);
  }
}

&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program &lt;/span&gt;{

  &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args) {
    &lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt; a = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt;();  &lt;span style="color: green"&gt;// if this compiled..&lt;/span&gt;
    a.AddNew();                 &lt;span style="color: green"&gt;// boom here!
  &lt;/span&gt;}

}&lt;/p&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;What’s the use of covariance if it causes runtime exceptions all the time, even for inherited classes?&amp;#160; Needless to say covariant/contravariant generics didn’t make it into the language yet.&amp;#160; &lt;/p&gt;

&lt;p&gt;But what if we know we have a situation where we need to make the cast and we know its safe.&amp;#160; All is not lost!&amp;#160; I won’t bore you with all the work I did to try to hack the exact layout of the internal MethodTable structure that is used to hold type information.&amp;#160; I got off track assuming that since there were definitions for covariant generic parameters that all I had to do was use a memory hack to turn on the the GenericParameterAttributes.Covariant flag in the T parameter for List&amp;lt;T&amp;gt;.&amp;#160; I almost got to the point where I could do that, except there is an internal handle based system for storing certain things and the attributes were stored in there.&amp;#160; I was unable to break into the handle storage…yet&amp;#160;&amp;#160; But that is for another day.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;a name="gohere"&gt;&lt;/a&gt;I ended up with this.&amp;#160; Note, unsafe code follows:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;p&gt;&lt;span style="color: blue"&gt;delegate &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt; &lt;span style="color: #2b91af"&gt;CCastDelegate&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt; b); &lt;/p&gt;&lt;p&gt;... &lt;/p&gt;&lt;p&gt;&lt;span style="color: #2b91af"&gt;DynamicMethod &lt;/span&gt;dynamicMethod = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DynamicMethod&lt;/span&gt;(&lt;br /&gt; &lt;span style="color: #a31515"&gt;&amp;quot;foo1&amp;quot;&lt;/span&gt;, &lt;br /&gt; &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt;), &lt;br /&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt;) }, &lt;br /&gt; &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue"&gt;void&lt;/span&gt;));&lt;br /&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color: #2b91af"&gt;ILGenerator &lt;/span&gt;il = dynamicMethod.GetILGenerator();
il.Emit(&lt;span style="color: #2b91af"&gt;OpCodes&lt;/span&gt;.Ldarg_0);  &lt;span style="color: green"&gt;// copy first argument  to stack
&lt;/span&gt;il.Emit(&lt;span style="color: #2b91af"&gt;OpCodes&lt;/span&gt;.Ret);      &lt;span style="color: green"&gt;// return the item on the stack
&lt;/span&gt;&lt;span style="color: #2b91af"&gt;CCastDelegate &lt;/span&gt;HopeThisWorks = (&lt;span style="color: #2b91af"&gt;CCastDelegate&lt;/span&gt;)&lt;br /&gt;&amp;#160; dynamicMethod.CreateDelegate(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;CCastDelegate&lt;/span&gt;));&lt;/p&gt;&lt;p&gt;... &lt;/p&gt;&lt;p&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt; = HopeThisWorks(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt;()); &lt;/p&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Basically, I created a very simple function using IL that takes a single parameter and returns it.&amp;#160; The parameter is define as a List&amp;lt;B&amp;gt; and the return is defined as a List&amp;lt;A&amp;gt;.&amp;#160; This simply bypasses the type safe checking that C# works so hard to maintain.&lt;/p&gt;

&lt;p&gt;My full test application code is here:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;p&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;System;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Collections.Generic;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Text;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Reflection.Emit;

&lt;span style="color: blue"&gt;namespace &lt;/span&gt;Covariant {

  &lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;A &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public virtual string &lt;/span&gt;Name() { &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #a31515"&gt;&amp;quot;A&amp;quot;&lt;/span&gt;; }
  }

  &lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;B &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;A &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public override string &lt;/span&gt;Name() { &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #a31515"&gt;&amp;quot;B&amp;quot;&lt;/span&gt;; }
  }

  &lt;span style="color: blue"&gt;delegate &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt; &lt;span style="color: #2b91af"&gt;CCastDelegate&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt; b);  &lt;span style="color: green"&gt;

  &lt;/span&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program &lt;/span&gt;{

    &lt;span style="color: blue"&gt;static unsafe &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt; CastBasAIL(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt; bIn) {

      &lt;span style="color: green"&gt;// This creates a simple IL function that takes a &lt;br /&gt;      // &lt;/span&gt;&lt;span style="color: green"&gt;parameter and returns it.
      // Since it takes it as one type and returns it as &lt;br /&gt;      // another, it bypasses the type checking

      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DynamicMethod &lt;/span&gt;dynamicMethod = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DynamicMethod&lt;/span&gt;(&lt;br /&gt;       &lt;span style="color: #a31515"&gt;&amp;quot;foo1&amp;quot;&lt;/span&gt;, &lt;br /&gt;       &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt;), &lt;br /&gt;       &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt;) }, &lt;br /&gt;       &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue"&gt;void&lt;/span&gt;));
      &lt;span style="color: #2b91af"&gt;ILGenerator &lt;/span&gt;il = dynamicMethod.GetILGenerator();
      il.Emit(&lt;span style="color: #2b91af"&gt;OpCodes&lt;/span&gt;.Ldarg_0);  &lt;span style="color: green"&gt;// copy first arg to stack
      &lt;/span&gt;il.Emit(&lt;span style="color: #2b91af"&gt;OpCodes&lt;/span&gt;.Ret);      &lt;span style="color: green"&gt;// return item on the stack
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CCastDelegate &lt;/span&gt;HopeThisWorks = (&lt;span style="color: #2b91af"&gt;CCastDelegate&lt;/span&gt;)&lt;br /&gt;       dynamicMethod.CreateDelegate(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;CCastDelegate&lt;/span&gt;));

      &lt;span style="color: blue"&gt;return &lt;/span&gt;HopeThisWorks(bIn);

    }

    &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args) {

      &lt;span style="color: green"&gt;// make a list&amp;lt;B&amp;gt;
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt; b = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;&amp;gt;();
      b.Add(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;());
      b.Add(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;());

      &lt;span style="color: green"&gt;// set list&amp;lt;A&amp;gt; = the list b using the work around
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt; a = CastBasAIL(b);
      
      &lt;span style="color: green"&gt;// at this point the debugger is miffed with a, but &lt;br /&gt;      // code executing methods of a work just fine.
      // It may be that the debugger simply checks that type&lt;br /&gt;      // of the generic argument matches the 
      // signature of the type, or it may be that something &lt;br /&gt;      // is really screwed up.  Nothing ever crashes.

      // prove the cast really worked
      &lt;/span&gt;TestA(a);

      &lt;span style="color: green"&gt;// add some more elements to B
      &lt;/span&gt;b.Add(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;B&lt;/span&gt;());

      &lt;span style="color: green"&gt;// element added to B shows up in A like we expected
      &lt;/span&gt;TestA(a);

      &lt;span style="color: blue"&gt;return&lt;/span&gt;;

    }

    &lt;span style="color: blue"&gt;static void &lt;/span&gt;TestA(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt; a) {

      &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Input type: {0}&amp;quot;&lt;/span&gt;, &lt;br /&gt;       &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;A&lt;/span&gt;&amp;gt;).ToString());
      &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Passed in type: {0}\n&amp;quot;&lt;/span&gt;, &lt;br /&gt;       a.GetType().ToString());

      &lt;span style="color: green"&gt;// Prove that A is B
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Count = {0}&amp;quot;&lt;/span&gt;, a.Count);
      &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Item.Name = {0}&amp;quot;&lt;/span&gt;, a[0].Name());

      &lt;span style="color: green"&gt;// see if more complicated methods of List&amp;lt;A&amp;gt; still work
      &lt;/span&gt;&lt;span style="color: blue"&gt;int &lt;/span&gt;i = a.FindIndex(&lt;br /&gt;       &lt;span style="color: blue"&gt;delegate&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;A &lt;/span&gt;item) { &lt;br /&gt;         &lt;span style="color: blue"&gt;return &lt;/span&gt;item.Name() == &lt;span style="color: #a31515"&gt;&amp;quot;A&amp;quot;&lt;/span&gt;; &lt;br /&gt;       }&lt;br /&gt;      );
      &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;br /&gt;       &lt;span style="color: #a31515"&gt;&amp;quot;Index of 1st A in List&amp;lt;A&amp;gt; = {0}&amp;quot;&lt;/span&gt;, i);
      i = a.FindIndex(&lt;br /&gt;       &lt;span style="color: blue"&gt;delegate&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;A &lt;/span&gt;item) { &lt;br /&gt;         &lt;span style="color: blue"&gt;return &lt;/span&gt;item.Name() == &lt;span style="color: #a31515"&gt;&amp;quot;B&amp;quot;&lt;/span&gt;; }&lt;br /&gt;      );
      &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;br /&gt;       &lt;span style="color: #a31515"&gt;&amp;quot;Index of 1st B in List&amp;lt;A&amp;gt; = {0}\n&amp;quot;&lt;/span&gt;, i);

      &lt;span style="color: green"&gt;// can we convert a to an array still?
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;br /&gt;       &lt;span style="color: #a31515"&gt;&amp;quot;Iterate through a, after converting a to an array&amp;quot;&lt;/span&gt;);
      &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;a.ToArray())
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0}&amp;quot;&lt;/span&gt;, x.Name());

    }

  }

}&lt;/p&gt;&lt;/pre&gt;

&lt;p&gt;Too bad I figured this all out after the interview!&amp;#160; &lt;/p&gt;

&lt;p&gt;Bear in mind, I developed and checked this on framework 3.5, under 32 bit windows XP.&amp;#160; I &lt;em&gt;think &lt;/em&gt;it will work on the other OS’s and address sizes, but I leave that exercise up to the reader.&amp;#160; Since this is an unsafe cast, the compiler is not protecting you from yourself.&amp;#160; You will get runtime errors and or crashes if you are not careful.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7162964-6357134090851400591?l=buiba.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://buiba.blogspot.com/feeds/6357134090851400591/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7162964&amp;postID=6357134090851400591' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/6357134090851400591'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/6357134090851400591'/><link rel='alternate' type='text/html' href='http://buiba.blogspot.com/2009/06/so-i-get-onto-phone-for-my-first-job.html' title='Hacking a C# Covariant Generic Cast Solution'/><author><name>johnnycrash</name><uri>http://www.blogger.com/profile/00685855809394991386</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7162964.post-8877880297529200945</id><published>2009-06-05T14:44:00.000-07:00</published><updated>2009-06-15T16:33:03.738-07:00</updated><title type='text'>Blogging for food</title><content type='html'>I decided to change my career during an economic downturn. Thus, I am finding myself with a lot of free time on my hands. I haven't looked for a job since college! I didn't realize how much work this would be.

I have found a bug in email.... All email clients and servers. Every one of em! Whenever you attach a resume to an email, the chances of the email getting delivered drop to near zero. At least I tell myself that this is why nearly all of resumes I have sent out receive no response!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7162964-8877880297529200945?l=buiba.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://buiba.blogspot.com/feeds/8877880297529200945/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7162964&amp;postID=8877880297529200945' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/8877880297529200945'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/8877880297529200945'/><link rel='alternate' type='text/html' href='http://buiba.blogspot.com/2009/06/blogging-for-food.html' title='Blogging for food'/><author><name>johnnycrash</name><uri>http://www.blogger.com/profile/00685855809394991386</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7162964.post-108598104163451289</id><published>2004-05-30T22:23:00.000-07:00</published><updated>2004-05-30T22:24:01.633-07:00</updated><title type='text'>First Post</title><content type='html'>Testing 123...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7162964-108598104163451289?l=buiba.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://buiba.blogspot.com/feeds/108598104163451289/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7162964&amp;postID=108598104163451289' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/108598104163451289'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7162964/posts/default/108598104163451289'/><link rel='alternate' type='text/html' href='http://buiba.blogspot.com/2004/05/first-post.html' title='First Post'/><author><name>johnnycrash</name><uri>http://www.blogger.com/profile/00685855809394991386</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>7</thr:total></entry></feed>
