<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;A0MDQHgycSp7ImA9WhBVF0U.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804</id><updated>2013-04-24T09:44:31.699+02:00</updated><category term="C#" /><category term="LINQ" /><category term="Code" /><category term="Compiler" /><category term="CLR" /><category term="CLI" /><category term="Constructors" /><category term="JIT" /><category term="Chaining" /><category term="UAC" /><category term="Excel 2007" /><category term="Private Implementation Detail" /><category term="HowTo" /><category term="Stack Trace" /><category term="spreadshhet" /><category term="SyntaxHighlighter" /><category term="datetime" /><category term="Windows7" /><category term="Breaking Change" /><category term="OpenXml" /><category term="Static" /><category term="Blog" /><category term="Assigment operator" /><category term="Inline" /><title>Coding By My Own Example</title><subtitle type="html">This blog will mostly be about my own coding experiences that I think would be nice to have a coding example on if ever I need to code something similar again.</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://blog.renttalent.dk/" /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>9</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/CodingByMyOwnExample" /><feedburner:info uri="codingbymyownexample" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry gd:etag="W/&quot;DEQBQHc9cSp7ImA9WhBQGUg.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804.post-824868866507899003</id><published>2013-03-20T12:26:00.003+01:00</published><updated>2013-03-22T13:45:51.969+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-03-22T13:45:51.969+01:00</app:edited><title>  Network shares not mapped across UAC boundaries - The code</title><content type="html">This is a short follow up on &lt;a href="http://blog.renttalent.dk/2012/12/network-shares-not-mapped-across-uac.html"&gt;this blog entry&lt;/a&gt;. This is the code for the concept I wrote about in that entry.&lt;br /&gt;
&lt;br /&gt;
Tweaks to make to the source ready for use:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;In the RegisterTask project, the file ReMount.xml under triggers there is a commented out line that need to be updated to the correct user. If the user is the one installing the UserId template from the Author tag can be used.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
The solution can be&lt;a href="http://bit.ly/13b6PTL" rel="nofollow" target="_blank"&gt; downloaded from here. &lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/CodingByMyOwnExample/~4/HsJGC7drrAo" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/824868866507899003/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://blog.renttalent.dk/2013/03/network-shares-not-mapped-across-uac.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/824868866507899003?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/824868866507899003?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~3/HsJGC7drrAo/network-shares-not-mapped-across-uac.html" title="  Network shares not mapped across UAC boundaries - The code" /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><thr:total>0</thr:total><gd:extendedProperty name="commentSource" value="1" /><gd:extendedProperty name="commentModerationMode" value="FILTERED_POSTMOD" /><feedburner:origLink>http://blog.renttalent.dk/2013/03/network-shares-not-mapped-across-uac.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D04GRX4-cSp7ImA9WhNWE08.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804.post-1918211041100833636</id><published>2012-12-12T16:24:00.000+01:00</published><updated>2012-12-12T16:25:24.059+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-12-12T16:25:24.059+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Windows7" /><category scheme="http://www.blogger.com/atom/ns#" term="UAC" /><title>Network shares not mapped across UAC boundaries</title><content type="html">After upgrading the OS on my workstation from Windows XP to Windows 7 I discovered that, suddenly, some files could not be opened from a network shares that was mapped on my computer when the program was running in elevated mode and the file that I wanted to open was activated by double clicking the item.
Also I discovered that when I used the "Open File" dialog from within the program all the network shares that was connected when using Explorer was now marked with a red X indicating that the connection was not established. Selecting the mapped drive would then connect the share and every thing would work as it used to for that share until the next time the computer was rebooted.&lt;br /&gt;
&lt;br /&gt;
This behavior was the effect of being restrained by the UAC introduced in Windows Vista and as an administrator on the computer you actually have two sessions when you are looged on to the system, one elevated an one restricted. These two sessions does not share context, and this also includes what network shares that are mapped and connected. So when you double click a file in Explorer to open it in the associated program, and that program is set to be elevated, then you have a scenario where a program in one context is asking to have a file opened in another context, but the program in the other context does not yet known that the mapped drive exists. Only when the mapped drive has been connected in the other context, i.e. by using the "Open File" dialog and making the drives connect will the context know that the drive is accessible, and this information will last until next time the user needs to perform a new log-on and thus creating new sessions.&lt;br /&gt;
&lt;br /&gt;
After searching the Internet for solutions to this problem, including understating what the underlying problem was, I ended up with two possible solution candidates&lt;br /&gt;
&lt;br /&gt;
The first possible solution was a change in registry as described in this article: &lt;a href="http://support.microsoft.com/kb/937624"&gt;Programs may be unable to access some network locations after you turn on User Account Control in Windows Vista or in Windows 7&lt;/a&gt;. The problem, in my view, with this solution is that it essentially just removed the security boundary, and then I could just as well turn UAC completely off, plus a change to the registry was needed that was not guaranteed to work going forward. So this method was not really what I wanted, and the search for solutions continued.&lt;br /&gt;
&lt;br /&gt;
As my search continued I got more and more frustrated that there was no apparent solution to this problem and I decided that it should be possible to create some kind of solution that would perform the task of entering the other security context, perform the equivalent of selecting an unconnected network share to get it reconnect.&lt;br /&gt;
&lt;br /&gt;
My reasoning was that explorer is able to show me the shares that are mapped and whether they are connected or not. So I should be able to extract that information as well.&lt;br /&gt;
&lt;br /&gt;
After a lot of digging around I ended up with a solution that uses some parts of Windows Management Instrumentation and some parts of Windows Shell Objects to accomplish the task.&lt;br /&gt;
&lt;br /&gt;
the WMI part is used for querying what shares are mapped, but not necessarily connected
and what drive letters is actually used for mounted drives. By comparing the two list I can then determine what shares that are not connected by seeing if the drive letter that is listed in the ManagementObject is also listed in the mounted drives list.&lt;br /&gt;
&lt;br /&gt;
And if the drive is not mounted, and is one of the shared that I want to have mounted I can then use the WSO to mount the share to the requested drive letter.&lt;br /&gt;
&lt;br /&gt;
A question may arise here of why I don't use WMI to map/mount the share as a drive. and the answer is that this was the fasted solution i could find at the time, and possibly not the best.&lt;br /&gt;
&lt;br /&gt;
This fine little application now just needs to be executed once in the other context (the elevated one in this case) and then the world view would be the same for the selected drives on both sides of the security context wall.&lt;br /&gt;
&lt;br /&gt;
Putting the program in the startup folder won't help you here, as Windows will block programs that require elevated privileges to avoid the elevation prompt at startup.&lt;br /&gt;
&lt;br /&gt;
To solve this little dilemma I found out that I could make a scheduled task that would run whenever I logged in that can then elevate the process to the correct context and thus problem solved.&lt;br /&gt;
&lt;br /&gt;
Just To make this solution deployable across the entire department where I work, I created an MSI installer that automatically created the task upon installation and removed on removal of tool, this is accomplished by using custom actions that uses the command line version of schtasks.exe&lt;img src="http://feeds.feedburner.com/~r/CodingByMyOwnExample/~4/__sx9bVJEKM" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/1918211041100833636/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://blog.renttalent.dk/2012/12/network-shares-not-mapped-across-uac.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/1918211041100833636?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/1918211041100833636?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~3/__sx9bVJEKM/network-shares-not-mapped-across-uac.html" title="Network shares not mapped across UAC boundaries" /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><thr:total>0</thr:total><gd:extendedProperty name="commentSource" value="1" /><gd:extendedProperty name="commentModerationMode" value="FILTERED_POSTMOD" /><feedburner:origLink>http://blog.renttalent.dk/2012/12/network-shares-not-mapped-across-uac.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkMHRns_eSp7ImA9WhNVEE4.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804.post-1149694562773412973</id><published>2010-09-02T13:57:00.000+02:00</published><updated>2012-12-20T22:20:37.541+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-12-20T22:20:37.541+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Compiler" /><category scheme="http://www.blogger.com/atom/ns#" term="Private Implementation Detail" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>What is the MSIL PrivateImplementationDetail</title><content type="html">&lt;b&gt;Digging in MSIL&lt;/b&gt;&lt;br /&gt;
As part of my work I sometimes have to verify that an installer contains only rebuild code for some of the sub modules. To achieve this I use the ildasm.exe tool to decompile the assemblies and then make a text comparison of the IL output.&lt;br /&gt;
&lt;br /&gt;
During examination of the output I encountered some weird  IL output that I couldn't directly map to the source code and that was changing every time the code was rebuild even though the source code didn't change. The characteristic of this output was always &amp;lt;privateimplementationdetails&amp;gt;{SOME GUID}.&lt;br /&gt;
&lt;br /&gt;
In an effort to understand what this was I tried googling for any information that could explain what this was and how I could verify that there actually was no source code change. But Google disappointed me and didn't give any answer.&lt;br /&gt;
&lt;br /&gt;
Instead I (and my colleague) started making code samples to get IL code with this &amp;lt;privateimplementationdetails&amp;gt; output. After some binary search in code known to produce this we found the code structure, or at lest one, that could reproduce this.&lt;br /&gt;
&lt;br /&gt;
The following code sample will show you code that both do and don't produce &amp;lt;privateimplementationdetails&amp;gt; in the IL output.&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;class CharClass
{
    char[] char_1 = new[] { 'a', 'b' };
    char[] char_2 = new[] { 'c', 'd', 'e' };
}
&lt;/pre&gt;
The resulting IL code looks like the following (excluding the meta data).&lt;br /&gt;
&lt;pre class="brush: MSIL"&gt;.class private auto ansi beforefieldinit CharClass
       extends [mscorlib]System.Object
{
  .field private char[] char_1
  .field private char[] char_2
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       55 (0x37)
    .maxstack  4
    .locals init ([0] char[] CS$0$0000)
    IL_0000:  ldarg.0
    IL_0001:  ldc.i4.2
    IL_0002:  newarr     [mscorlib]System.Char
    IL_0007:  stloc.0
    IL_0008:  ldloc.0
    IL_0009:  ldc.i4.0
    IL_000a:  ldc.i4.s   97
    IL_000c:  stelem.i2
    IL_000d:  ldloc.0
    IL_000e:  ldc.i4.1
    IL_000f:  ldc.i4.s   98
    IL_0011:  stelem.i2
    IL_0012:  ldloc.0
    IL_0013:  stfld      char[] CharClass::char_1
    IL_0018:  ldarg.0
    IL_0019:  ldc.i4.3
    IL_001a:  newarr     [mscorlib]System.Char
    IL_001f:  dup
    IL_0020:  ldtoken    field valuetype '&amp;lt;privateimplementationdetails&amp;gt;{F325A222-827B-4DCA-B78A-B2EC85FEBAD3}'/'__StaticArrayInitTypeSize=6' '&amp;lt;privateimplementationdetails&amp;gt;{F325A222-827B-4DCA-B78A-B2EC85FEBAD3}'::'$$method0x6000001-1'
    IL_0025:  call       void [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
    IL_002a:  stfld      char[] CharClass::char_2
    IL_002f:  ldarg.0
    IL_0030:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0035:  nop
    IL_0036:  ret
  } // end of method CharClass::.ctor

} // end of class CharClass

.class private auto ansi '&amp;lt;privateimplementationdetails&amp;gt;{F325A222-827B-4DCA-B78A-B2EC85FEBAD3}'
       extends [mscorlib]System.Object
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
  .class explicit ansi sealed nested private '__StaticArrayInitTypeSize=6'
         extends [mscorlib]System.ValueType
  {
    .pack 1
    .size 6
  } // end of class '__StaticArrayInitTypeSize=6'

  .field static assembly valuetype '&amp;lt;privateimplementationdetails&amp;gt;{F325A222-827B-4DCA-B78A-B2EC85FEBAD3}'/'__StaticArrayInitTypeSize=6' '$$method0x6000001-1' at I_00002050
} // end of class '&amp;lt;privateimplementationdetails&amp;gt;{F325A222-827B-4DCA-B78A-B2EC85FEBAD3}'

// =============================================================

.data cil I_00002050 = bytearray (
                 63 00 64 00 65 00)                               // c.d.e.
&lt;/pre&gt;
&lt;br /&gt;
As it's clear from the IL there is clearly a difference between assigning a char array with 2 and 3 elements. This goes for most value types tested (summary at the end).&lt;br /&gt;
&lt;br /&gt;
Expanding the the search to reference types the following was observed.&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;class ObjectClass
{
    object[] Object_1 = new[] { new object(), new object() };
    object[] Object_2 = new[] { new object(), new object(), new object() };
}
&lt;/pre&gt;
Results in&lt;br /&gt;
&lt;pre class="brush: MSIL"&gt;.class private auto ansi beforefieldinit ObjectClass
       extends [mscorlib]System.Object
{
  .field private object[] Object_1
  .field private object[] Object_2
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       76 (0x4c)
    .maxstack  4
    .locals init ([0] object[] CS$0$0000)
    IL_0000:  ldarg.0
    IL_0001:  ldc.i4.2
    IL_0002:  newarr     [mscorlib]System.Object
    IL_0007:  stloc.0
    IL_0008:  ldloc.0
    IL_0009:  ldc.i4.0
    IL_000a:  newobj     instance void [mscorlib]System.Object::.ctor()
    IL_000f:  stelem.ref
    IL_0010:  ldloc.0
    IL_0011:  ldc.i4.1
    IL_0012:  newobj     instance void [mscorlib]System.Object::.ctor()
    IL_0017:  stelem.ref
    IL_0018:  ldloc.0
    IL_0019:  stfld      object[] ObjectClass::Object_1
    IL_001e:  ldarg.0
    IL_001f:  ldc.i4.3
    IL_0020:  newarr     [mscorlib]System.Object
    IL_0025:  stloc.0
    IL_0026:  ldloc.0
    IL_0027:  ldc.i4.0
    IL_0028:  newobj     instance void [mscorlib]System.Object::.ctor()
    IL_002d:  stelem.ref
    IL_002e:  ldloc.0
    IL_002f:  ldc.i4.1
    IL_0030:  newobj     instance void [mscorlib]System.Object::.ctor()
    IL_0035:  stelem.ref
    IL_0036:  ldloc.0
    IL_0037:  ldc.i4.2
    IL_0038:  newobj     instance void [mscorlib]System.Object::.ctor()
    IL_003d:  stelem.ref
    IL_003e:  ldloc.0
    IL_003f:  stfld      object[] ObjectClass::Object_2
    IL_0044:  ldarg.0
    IL_0045:  call       instance void [mscorlib]System.Object::.ctor()
    IL_004a:  nop
    IL_004b:  ret
  } // end of method ObjectClass::.ctor

} // end of class ObjectClass
&lt;/pre&gt;
Clearly reference types do not get the same treatment as value types.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;What is this &amp;lt;privateimplementationdetails&amp;gt; anyway?&lt;/b&gt;&lt;br /&gt;
To the best of my knowledge, and this is only an educated guess from what I have observed, these private implementation details are just that. something that the C# compiler does behind your back, presumably to preserve stack usage.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;What types get this treatment?&lt;/b&gt;&lt;br /&gt;
As far as I have observed, again this is not meant to be an exhaustive list, the numeric value types behaves this way. That is byte, sbyte, short, ushort, int, uint, long, ulong, float and double. When using reference types this compiler trick doesn't seem to invoked.&lt;br /&gt;
&lt;br /&gt;
It's also worth noting that even though enums are value types they are treated like reference types in this case. String, known to get special treatment are also just reference types in this case.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;When can I expect this behavior from the compiler?&lt;/b&gt;&lt;br /&gt;
I have only seen the &amp;lt;privateimplementationdetails&amp;gt; been generated by the C# compiler. I have tried making the equivalent code in VB.NET and they just replicate the way C# handles 2 items, by using the stack for each element. In C# I have tried with version 2.0 and 4, both version produces the same IL code.&lt;img src="http://feeds.feedburner.com/~r/CodingByMyOwnExample/~4/fGgp6QDwcJ4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/1149694562773412973/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://blog.renttalent.dk/2010/09/what-is-msil-privateimplementationdetai.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/1149694562773412973?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/1149694562773412973?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~3/fGgp6QDwcJ4/what-is-msil-privateimplementationdetai.html" title="What is the MSIL PrivateImplementationDetail" /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><thr:total>0</thr:total><gd:extendedProperty name="commentSource" value="1" /><gd:extendedProperty name="commentModerationMode" value="FILTERED_POSTMOD" /><feedburner:origLink>http://blog.renttalent.dk/2010/09/what-is-msil-privateimplementationdetai.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CU4NRXg_fyp7ImA9Wx5QE0k.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804.post-4180328615759166226</id><published>2010-08-31T13:34:00.001+02:00</published><updated>2010-09-01T14:26:34.647+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-09-01T14:26:34.647+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Breaking Change" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="CLI" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><category scheme="http://www.blogger.com/atom/ns#" term="Code" /><category scheme="http://www.blogger.com/atom/ns#" term="CLR" /><title>CLI VS C# and the meaning of cast.</title><content type="html">&lt;b&gt;What is a cast operation actually?&lt;/b&gt;&lt;br /&gt;
Well, that depends. Do you see the worlds from the C# language or from the CLI world.&lt;br /&gt;
&lt;br /&gt;
This article is based on my experience using C# 3.5 SP1 and I have no idea if it applies to other .NET Language.&lt;br /&gt;
&lt;br /&gt;
I was in a situation where an API call returned an int[] and I needed to use those values with an other API call but as a double[]. Looking at what immediate option the IntelliSense in Visual Studio showed me I found the Cast&amp;lt;t&amp;gt; and thought that this is just what I need for this job.&lt;br /&gt;
&lt;br /&gt;
To my surprise, when running the code a runtime exception of System.InvalidCastException is thrown. My initial thought was why doesn't this work? The Cast&amp;lt;t&amp;gt; comes from the IEnumerable interface, thus if there exists an implicit conversion from one type to the other the cast should be possible. So why ins't it?&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Looking at the specifications.&lt;/b&gt;&lt;br /&gt;
Reading the MSDN entry for IEnumerable.Cast&amp;lt;t&amp;gt; didn't give me any insight to why this didn't work&lt;br /&gt;
&lt;br /&gt;
The C# Language Specification 7.6.6 defines the cast expression (T)E to be an explicit conversion(so this is why I think the name Cast&amp;lt;T&amp;gt; sucks).&lt;br /&gt;
Also 6.1.2 specifies a list if allowed implicit conversions.&lt;br /&gt;
&lt;br /&gt;
Looking at ECMA-335 chap 8.3.3 could explain why they have made this particular implementation.&lt;br /&gt;
&lt;blockquote&gt;Unlike coercion, a cast never changes the actual type of&lt;br /&gt;
an object nor does it change the representation. Casting preserves the identity of objects.&lt;/blockquote&gt;Searching around on the Internet it does looks like it has worked as I would expect from the name (From C# definition) before 3.5 sp1&lt;br /&gt;
&lt;a href="http://blogs.msdn.com/b/ed_maurer/archive/2008/02/16/breaking-change-in-linq-queries-using-explicitly-typed-range-variables.aspx"&gt;For instance this article&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Cast&amp;lt;t&amp;gt; for IEnumerable should really be Unbox&amp;lt;t&amp;gt; or something similar to make it visible that you can only perform this on objects that are in the same line of inheritance.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Ways around this technical implementation detail&lt;/B&gt;&lt;br /&gt;
To find out how to get the wanted result I tried to think of ways to implement the wanted behavior and then time the time it takes to see what is the best way. I tried to make a generic approach as to find any other limitations that the different implementations might have.&lt;br /&gt;
&lt;br /&gt;
I found 5 approaches that could be feasible:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;An implicit cast using the Array.CopyTo method.&lt;/li&gt;
&lt;li&gt;The IEnumerable.Cast&amp;lt;T&amp;gt; (Just to make sure it wasn't just my specific case that made problems).&lt;/li&gt;
&lt;li&gt;Use a LINQ query with Convert.ChangeType.&lt;/li&gt;
&lt;li&gt;Use Array.ConvertAll with Convert.ChangeType.&lt;/li&gt;
&lt;li&gt;Use Convert.ChangeType directly on the arrys.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
That resulted in the following code:&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace TransformArrays
{
    class Program
    {
        private static void DoImplcitConversion&amp;lt;T1, T2&amp;gt;(T1&amp;#91;&amp;#93; fromArray, out T2&amp;#91;&amp;#93; toArray)
        {
            code = Code.ImplcitWithArray_CopyTo;
            Console.WriteLine("Implicit conversion from {0}&amp;#91;&amp;#93; to {1}&amp;#91;&amp;#93; using Array.CopyTo with {2} elemets", typeof(T1).Name, typeof(T2).Name, fromArray.Length);
            try
            {
                Stopwatch watch = StartNew();
                toArray = new T2&amp;#91;fromArray.Length&amp;#93;;
                fromArray.CopyTo(toArray, 0);
                StopStopwatch(watch);
            }
            catch
            {
                toArray = null;
                Console.WriteLine(ExceptionMgs);
            }
        }

        private static void DoChangeType&amp;lt;T1, T2&amp;gt;(T1&amp;#91;&amp;#93; fromArray, out T2&amp;#91;&amp;#93; toArray)
        {
            code = Code.ChangeTypeOnArrays;
            Console.WriteLine("Convert.ChangeType from {0}&amp;#91;&amp;#93; to {1}&amp;#91;&amp;#93; using Array.CopyTo with {2} elemets", typeof(T1).Name, typeof(T2).Name, fromArray.Length);
            try
            {
                Stopwatch watch = StartNew();
                toArray = (T2&amp;#91;&amp;#93;)System.Convert.ChangeType(fromArray, typeof(T2&amp;#91;&amp;#93;));
                StopStopwatch(watch);
            }
            catch
            {
                toArray = null;
                Console.WriteLine(ExceptionMgs);
            }
        }

        private static void DoCast&amp;lt;T1, T2&amp;gt;(T1&amp;#91;&amp;#93; fromArray, out T2&amp;#91;&amp;#93; toArray)
        {
            code = Code.Cast;
            Console.WriteLine("Using IEnumerable.Cast&amp;lt;&amp;gt; to change from {0}&amp;#91;&amp;#93; to {1}&amp;#91;&amp;#93; with {2} elemets", typeof(T1).Name, typeof(T2).Name, fromArray.Length);
            try
            {
                Stopwatch watch = StartNew();
                toArray = fromArray.Cast&amp;lt;t2&amp;gt;().ToArray();
                StopStopwatch(watch);
            }
            catch
            {
                toArray = null;
                Console.WriteLine(ExceptionMgs);
            }
        }

        private static void DoConversionWithLambdaAndLinq&amp;lt;T1, T2&amp;gt;(T1&amp;#91;&amp;#93; fromArray, out T2&amp;#91;&amp;#93; toArray)
        {
            code = Code.Linq_SelectWithChangeType;
            Console.WriteLine("Using IEnumerable&amp;lt;&amp;gt;.Selectx =&amp;gt; ({1})Convert.ChangeType(x, typeof({1}))).ToArray() to change from {0}&amp;#91;&amp;#93; to {1}&amp;#91;&amp;#93; with {2} elemets", typeof(T1).Name, typeof(T2).Name, fromArray.Length);
            try
            {
                Stopwatch watch = StartNew();
                toArray = fromArray.Select(x =&amp;gt; (T2)Convert.ChangeType(x, typeof(T2))).ToArray();
                StopStopwatch(watch);
            }
            catch
            {
                toArray = null;
                Console.WriteLine(ExceptionMgs);
            }
        }
        
        private static void DoConversionWithLambdaAndArrayConvert&amp;lt;T1, T2&amp;gt;(T1&amp;#91;&amp;#93; fromArray, out T2&amp;#91;&amp;#93; toArray)
        {
            code = Code.Array_ConvertAllWithChangeType;
            Console.WriteLine("Using Array.ConvertAll&amp;lt;&amp;gt;(Input, x =&amp;gt; ({1})Convert.ChangeType(x, typeof({1}))) to change from {0}&amp;#91;&amp;#93; to {1}&amp;#91;&amp;#93; with {2} elemets", typeof(T1).Name, typeof(T2).Name, fromArray.Length);
            try
            {
                Stopwatch watch = StartNew();
                toArray = Array.ConvertAll(fromArray, x =&amp;gt; (T2)Convert.ChangeType(x, typeof(T2)));
                StopStopwatch(watch);
            }
            catch
            {
                toArray = null;
                Console.WriteLine(ExceptionMgs);
            }
        }

         /******************************************************************************
         *                                                                             *
         *                Code below is for running the examplas and                   *
         *                        collecting data code only.                           *
         *                                                                             *
         ******************************************************************************/

        enum Code { ImplcitWithArray_CopyTo, Cast, Linq_SelectWithChangeType, Array_ConvertAllWithChangeType, ChangeTypeOnArrays };
        enum FromTo { IntDouble, DoubleInt }

        static int Iterations = 25;
        static Code code = Code.ImplcitWithArray_CopyTo;
        static FromTo fromTo = FromTo.IntDouble;
        static string TimerMgs = "Execution took {0}" + Environment.NewLine;
        static string ExceptionMgs = "Exception thrown" + Environment.NewLine;
        static Dictionary&amp;lt;FromTo, Dictionary&amp;lt;Code, TimeSpan&amp;gt;&amp;gt; timeCollection = new Dictionary&amp;lt;FromTo, Dictionary&amp;lt;Code, TimeSpan&amp;gt;&amp;gt;();
        static double&amp;#91;&amp;#93; doubles = Enumerable.Range(1, 10000000).Select(x =&amp;gt; (double)x).ToArray();
        static int&amp;#91;&amp;#93; ints = Enumerable.Range(1, 10000000).ToArray();

        static void Main(string&amp;#91;&amp;#93; args)
        {
            for (int i = 0; i &amp;lt; Iterations; i++)
            {
                Console.WriteLine("round {0}", i + 1);
                FromIntToDouble();
                Console.WriteLine();
                FromDoubleToInt();
            }

            foreach (var ft in timeCollection.Keys)
            {
                foreach (var c in timeCollection&amp;#91;ft&amp;#93;.Keys)
                {
                    Console.WriteLine("{0}, {1} : {2}", ft.ToString(), c.ToString().PadRight(8, ' '), timeCollection&amp;#91;ft&amp;#93;&amp;#91;c&amp;#93;.TotalMilliseconds / Iterations);
                }
            }
        }

        private static void FromDoubleToInt()
        {
            fromTo = FromTo.DoubleInt;
            int&amp;#91;&amp;#93; ints = null;
            DoImplcitConversion&amp;lt;double, int&amp;gt;(doubles, out ints);
            DoCast&amp;lt;double, int&amp;gt;(doubles, out ints);
            DoConversionWithLambdaAndLinq&amp;lt;double, int&amp;gt;(doubles, out ints);
            DoConversionWithLambdaAndArrayConvert&amp;lt;double, int&amp;gt;(doubles, out ints);
            DoChangeType&amp;lt;double, int&amp;gt;(doubles, out ints);
        }

        private static void FromIntToDouble()
        {
            fromTo = FromTo.IntDouble;
            double&amp;#91;&amp;#93; doubles = null;
            DoImplcitConversion&amp;lt;int, double&amp;gt;(ints, out doubles);
            DoCast&amp;lt;int, double&amp;gt;(ints, out doubles);
            DoConversionWithLambdaAndLinq&amp;lt;int, double&amp;gt;(ints, out doubles);
            DoConversionWithLambdaAndArrayConvert&amp;lt;int, double&amp;gt;(ints, out doubles);
            DoChangeType&amp;lt;int, double&amp;gt;(ints, out doubles);
        }

        public static Stopwatch StartNew()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            return sw;
        }

        public static void StopStopwatch(Stopwatch sw)
        {
            sw.Stop();
            Console.WriteLine(TimerMgs, sw.Elapsed);
            if (!timeCollection.ContainsKey(fromTo))
            {
                timeCollection.Add(fromTo, new Dictionary&amp;lt;Code, TimeSpan&amp;gt;());
            }

            if (!timeCollection&amp;#91;fromTo&amp;#93;.ContainsKey(code))
            {
                timeCollection&amp;#91;fromTo&amp;#93;.Add(code, new TimeSpan());
            }
            timeCollection&amp;#91;fromTo&amp;#93;&amp;#91;code&amp;#93; += sw.Elapsed;
        }
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Benchmark results&lt;/b&gt;&lt;br /&gt;
I have tried making some benchmark of the different way of converting by making large arrays of 10.000.000 item and convert the data into another type 25 times. &lt;br /&gt;
&lt;br /&gt;
This is the results&lt;br /&gt;
&lt;pre&gt;|-------------------------------------------|
|              |  double-&amp;gt;int | int-&amp;gt;double |
|--------------+--------------+-------------|
| Implcit      |       N/A    |      145 ms |
|--------------+--------------+-------------|
| ConvertAll   |      2015 ms |     1659 ms |
|--------------+--------------+-------------|
| Select       |      3003 ms |     2568 ms |
|--------------+--------------+-------------|
| Cast&amp;gt;T&amp;lt;      |       N/A    |      N/A    |
|--------------+--------------+-------------|
| Array Change |       N/A    |      N/A    |
|-------------------------------------------|
&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodingByMyOwnExample/~4/OVzIvWfNqew" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/4180328615759166226/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://blog.renttalent.dk/2010/08/cli-vs-c-and-meaning-of-cast.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/4180328615759166226?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/4180328615759166226?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~3/OVzIvWfNqew/cli-vs-c-and-meaning-of-cast.html" title="CLI VS C# and the meaning of cast." /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><thr:total>0</thr:total><gd:extendedProperty name="commentSource" value="1" /><gd:extendedProperty name="commentModerationMode" value="FILTERED_POSTMOD" /><feedburner:origLink>http://blog.renttalent.dk/2010/08/cli-vs-c-and-meaning-of-cast.html</feedburner:origLink><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="enclosure" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~5/TRYqmBjBqD0/breaking-change-in-linq-queries-using-explicitly-typed-range-variables.aspx" length="0" type="Text/HTML" /><feedburner:origEnclosureLink>http://blogs.msdn.com/ed_maurer/archive/2008/02/16/breaking-change-in-linq-queries-using-explicitly-typed-range-variables.aspx</feedburner:origEnclosureLink></entry><entry gd:etag="W/&quot;DkYEQnc-fip7ImA9Wx5QE0k.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804.post-6660602747614339842</id><published>2010-07-08T11:36:00.002+02:00</published><updated>2010-09-01T14:28:23.956+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-09-01T14:28:23.956+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Assigment operator" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Chaining" /><title>A little caution note on chaining compound assignment.</title><content type="html">First of, what is a compound assignment.? A compound assignment is when you use an operator in conjunction with the assignment operator&lt;br /&gt;
&lt;pre class="brush: c-sharp"&gt;a += b; // The same as a = a + b
&lt;/pre&gt;Now consider that you want to write a swap routine using XOR&lt;br /&gt;
&lt;pre class="brush: c-sharp"&gt;a=a^b;
b=a^b;
a=a^b;
&lt;/pre&gt;this could be transformed to compound operators&lt;br /&gt;
&lt;pre class="brush: c-sharp"&gt;a^=b;
b^=a;
a^=b;
&lt;/pre&gt;If you haven't read the spec on how assignments works, you would think  that chaining these operators would be the same&lt;br /&gt;
&lt;pre class="brush: c-sharp"&gt;a^=b^=a^=b;
&lt;/pre&gt;But you will be surprised to learn that the latter two pieces of code behave differently.&lt;br /&gt;
&lt;br /&gt;
Chapter 7.16.2 in the C# specification explains what is going on. When using the compound operator the left side operand is evaluated only once. this means in practice that when you chain the operators like in the last example, then all the left side operands are evaluated before any execution, thus&amp;nbsp; the chain doesn't get the intermediate a and b updated as when you make it line by line.&lt;img src="http://feeds.feedburner.com/~r/CodingByMyOwnExample/~4/0RKlHr87IcI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/6660602747614339842/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://blog.renttalent.dk/2010/07/little-caution-note-on-chaining.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/6660602747614339842?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/6660602747614339842?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~3/0RKlHr87IcI/little-caution-note-on-chaining.html" title="A little caution note on chaining compound assignment." /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><thr:total>0</thr:total><gd:extendedProperty name="commentSource" value="1" /><gd:extendedProperty name="commentModerationMode" value="FILTERED_POSTMOD" /><feedburner:origLink>http://blog.renttalent.dk/2010/07/little-caution-note-on-chaining.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkUDQXYyfCp7ImA9Wx5QE0k.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804.post-6403239401514154219</id><published>2010-03-16T14:19:00.001+01:00</published><updated>2010-09-01T14:31:10.894+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-09-01T14:31:10.894+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Compiler" /><category scheme="http://www.blogger.com/atom/ns#" term="Constructors" /><category scheme="http://www.blogger.com/atom/ns#" term="Static" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Code" /><title>Why is my static constructor not called?</title><content type="html">&lt;span xmlns=''&gt;&lt;p&gt;In an effort to streamline the use of some utility code that we use for our different products I learned a lesson that I think not many programmers think about. And that is how the compiler, IntelliSense, inheritance and static methods work together.&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;The problem that I encountered was the following:&lt;br /&gt;
The utility code contains a print method that will traverse any object and print it out.&lt;br /&gt;
The print method has a bunch of overloads for various formatters and other stuff (this is not included in the sample code as this is trivial).&lt;br /&gt;
There exists other utility code that derives from the basic utility code to handle known objects in a non-generic way.&lt;br /&gt;
These derived utility methods should have all the overloads that only act as proxies for the real print implementation, available without the need for making signature hiding with the new keyword to get the right method called.&lt;br /&gt;
Any changes to the code must not break any old code using this utility code.&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;My starting point was code that looks like this:&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;&lt;pre class="brush: csharp"&gt;namespace before
{
    using System;
    public class UtilClass
    {
        public static void Print(object data)
        {
            Print(data, true, 0);
        }

        public static void Print(object data, bool recurse)
        {
            Print(data, true, 0);
        }

        protected static void Print(object data, bool recurse, int depth)
        {
            Console.WriteLine(string.Format("Base class with data {0}", data));
        }
    }

    public class SpecificClass : UtilClass
    {
        new public static void Print(object data)
        {
            Print(data, true, 0);
        }

        new public static void Print(object data, bool recurse)
        {
            Print(data, true, 0);
        }

        new protected static void Print(object data, bool recurse, int depth)
        {
            Console.WriteLine(string.Format("Derived class with data {0}", data));
            UtilClass.Print(data, recurse);
        }
    }

    public class Program
    {
        static void Main()
        {
            UtilClass.Print("Call to Base");
            SpecificClass.Print("Call to Derived");
        }
    }
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;As you can see, all methods are static, and I thought that, hey, why not make some sort of Singleton implementation which is controlled by the specific utility implementation and make a virtual print method that gets called by the static code and can then be overridden by any of the specific implementations, as the execution context will always be only one of the specific implementations, this should not introduce any conflicts. Only one specific implementation would be active at a time.&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;So I made some changes to the original code and was quite surprised with what happened. The code looked like this:&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;&lt;pre class="brush: csharp"&gt;namespace intend
{
    using System;

    public class UtilClass
    {
        protected static UtilClass instance = new UtilClass();
        public static void Print(object data)
        {
            instance.Print(data, true, 0);
        }

        public static void Print(object data, bool recurse)
        {
            instance.Print(data, recurse, 0);
        }

        protected virtual void Print(object data, bool recurse, int depth)
        {
            Console.WriteLine(string.Format("Base class with data {0}", data));
        }
    }

    public class SpecificClass : UtilClass
    {
        static SpecificClass()
        {
            instance = new SpecificClass();
        }

        protected override void Print(object data, bool recurse, int depth)
        {
            Console.WriteLine(string.Format("Derived class with data {0}", data));
            base.Print(data, true, 0);
        }
    }

    public class Program
    {
        static void Main()
        {
            UtilClass.Print("Call to Base");
            SpecificClass.Print("Call to Derived");
        }
    }
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;That's it, make the working methods to a virtual and an override, introduce an instance reference and make the type constructor update the instance reference to point to an object of the correct type. Remove the old overload methods from the specific implementation&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;What would you expect the outcome of the code from main is?&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;Base class with data Call to Base&lt;br /&gt;
Derived class with data Call to Derived&lt;br /&gt;
Base class with data Call to Derived&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;Or&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;Base class with data Call to Base&lt;br /&gt;
Base class with data Call to Derived&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;If you guessed the second output, then you are correct. And the reason: The type constructor for SpecificClass is never executed.&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;Why? Well the compiler makes some interpreting on the code, before spitting out IL. What the compiler sees is that the call to SpecificClass.Print is in fact a call to UtilClass.Print and will substitute the type, thus a reference to SpecificClass no longer exists, and the type constructor will never be called.&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;My final solution ended up being that I need to swallow the hit for the existing overloads and force any new code not to use these overloads by marking them obsolete.&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;The singleton idea is still valid, but I was not able to make the automatic selection of which flavor of the specialized class to use work with this way of implementing it.&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;The solution builds on a base class which has all the static void Print() overloads that is desired which work as proxies to the protected virtual instance method, and a protected singleton instance of itself for the proxies to call. Any existing derived classes will then have to stub out the already implemented static void print() with a setting of the flavor to a type of itself, and then calling the Print() on the instance. The end result looks a little something like this:&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;&lt;pre class="brush: csharp"&gt;namespace Solution
{
    using System;

    public class UtilClass
    {
        protected static UtilClass instance = new UtilClass();

        public static void SetFlavor&lt;t&gt;(T type) where T : UtilClass
        {
            UtilClass.instance = type;
        }

        public static void Print(object data)
        {
            instance.Print(data, true, 0);
        }

        public static void Print(object data, bool recurse)
        {
            instance.Print(data, recurse, 0);
        }

        protected virtual void Print(object data, bool recurse, int depth)
        {
            Console.WriteLine(string.Format("Base class with data {0}", data));
        }
    }

    public class SpecificClass : UtilClass
    {
        new public static void Print(object data)
        {
            SpecificClass.SetFlavor(new SpecificClass());
            (instance as SpecificClass).Print(data, true, 0);
        }

        new public static void Print(object data, bool recurse)
        {
            SpecificClass.SetFlavor(new SpecificClass());
            (instance as SpecificClass).Print(data, true, 0);
        }

        protected override void Print(object data, bool recurse, int depth)
        {
            Console.WriteLine(string.Format("Derived class with data {0}", data));
            base.Print(data, true, 0);
        }
    }

    public class Program
    {
        static void Main()
        {
            UtilClass.Print("Call to Base");
            SpecificClass.SetFlavor(new SpecificClass());
            SpecificClass.Print("Call to Derived");
        }
    }
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;If you have a more elegant solution than this, I would be happy se see your suggestion in the comments.&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;&lt;br /&gt;
 &lt;/p&gt;&lt;p&gt;Some of the reading material I have read through to solve this mystery.&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;&lt;a href='http://www.yoda.arachsys.com/csharp/beforefieldinit.html'&gt;http://www.yoda.arachsys.com/csharp/beforefieldinit.html&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;a href='http://ondotnet.com/pub/a/dotnet/2003/07/07/staticxtor.html'&gt;http://ondotnet.com/pub/a/dotnet/2003/07/07/staticxtor.html&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;a href='http://bytes.com/topic/c-sharp/answers/258322-static-constructor-derived-class'&gt;http://bytes.com/topic/c-sharp/answers/258322-static-constructor-derived-class&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;a href='http://bytes.com/topic/c-sharp/answers/496182-invoking-static-constructors-base-classes'&gt;http://bytes.com/topic/c-sharp/answers/496182-invoking-static-constructors-base-classes&lt;/a&gt;&lt;br /&gt;
&lt;/p&gt;&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/CodingByMyOwnExample/~4/a0AqDetOxZg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/6403239401514154219/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://blog.renttalent.dk/2010/03/why-is-my-static-constructor-not-called.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/6403239401514154219?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/6403239401514154219?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~3/a0AqDetOxZg/why-is-my-static-constructor-not-called.html" title="Why is my static constructor not called?" /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><thr:total>0</thr:total><gd:extendedProperty name="commentSource" value="1" /><gd:extendedProperty name="commentModerationMode" value="FILTERED_POSTMOD" /><feedburner:origLink>http://blog.renttalent.dk/2010/03/why-is-my-static-constructor-not-called.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkACRXozfip7ImA9Wx5QE0k.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804.post-2167178504401622120</id><published>2010-01-27T10:13:00.005+01:00</published><updated>2010-09-01T14:39:24.486+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-09-01T14:39:24.486+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="HowTo" /><category scheme="http://www.blogger.com/atom/ns#" term="SyntaxHighlighter" /><category scheme="http://www.blogger.com/atom/ns#" term="Blog" /><title>Getting SyntaxHighlighter to work with Blogger.com</title><content type="html">&lt;span style="font-size:130%;"&gt;Just a quick guide to get SyntaxHighlighter to work with Blogger.com&lt;/span&gt;&lt;br /&gt;
Step 1 - Get the code:&lt;br /&gt;
Download the source from &lt;a href="http://alexgorbatchev.com/wiki/SyntaxHighlighter:Download"&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Step 2 - Change the JavaScript:&lt;br /&gt;
src/shCore.js&lt;br /&gt;
On line 99:&lt;br /&gt;
I found these flags, which I turned on.&lt;br /&gt;
&lt;pre class="brush: js"&gt;/** Blogger mode flag. */

bloggerMode : true,

stripBrs : true, 
&lt;/pre&gt;&lt;br /&gt;
And after line 1198 I added the following line of code&lt;br /&gt;
&lt;pre class="brush: js"&gt;code.replace(/&lt;br\s*\/?&gt;/gi,'\n')
&lt;/pre&gt;&lt;br /&gt;
Step 3 - Host the script:&lt;br /&gt;
Find somewhere to host the SyntaxHighlighter  code on the net.&lt;br /&gt;
&lt;br /&gt;
Step 4 - &lt;a href="http://alexgorbatchev.com/wiki/SyntaxHighlighter:Usage"&gt;&lt;br /&gt;
Setup&lt;/a&gt;:&lt;br /&gt;
Follow the guide to setup.&lt;br /&gt;
When adding the link ans script references you need to change the HTML of the template. As the last part of the &amp;lt;head&amp;gt; section add the following&lt;br /&gt;
&lt;pre class="brush: xml"&gt;&amp;lt;script src='http://YOURHOST/src/shCore.js' type='text/javascript'/&amp;gt;
&amp;lt;script src='http://YOURHOST/scripts/shBrushCSharp.js' type='text/javascript'/&amp;gt;
&amp;lt;script src='http://YOURHOST/scripts/shBrushXml.js' type='text/javascript'/&amp;gt;
&amp;lt;link href='http://YOURHOST/styles/shCore.css' rel='stylesheet' type='text/css'/&amp;gt;
&amp;lt;link href='http://YOURHOST/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/&amp;gt;
&amp;lt;script type='text/javascript'&amp;gt;
SyntaxHighlighter.config.clipboardSwf = 'http://YOURHOST/scripts/clipboard.swf';
SyntaxHighlighter.all();
&amp;lt;/script&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
As you ca see I have added the cSharp and Xml brush, but you can change that to your own needs.&lt;br /&gt;
&lt;br /&gt;
Step 5 - Embed code in your posts.&lt;br /&gt;
Now you can  embed code snippets into you posts using the script tag:&lt;br /&gt;
&lt;pre class="brush: js"&gt;&amp;lt;script type="syntaxhighlighter" class="brush: js"&amp;gt;&amp;lt;![CDATA[
]]&amp;gt;&amp;lt;/script&amp;gt;
&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodingByMyOwnExample/~4/fm9kfrrluS4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/2167178504401622120/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://blog.renttalent.dk/2010/01/getting-syntaxhighlighter-to-work-with.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/2167178504401622120?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/2167178504401622120?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~3/fm9kfrrluS4/getting-syntaxhighlighter-to-work-with.html" title="Getting SyntaxHighlighter to work with Blogger.com" /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><thr:total>0</thr:total><gd:extendedProperty name="commentSource" value="1" /><gd:extendedProperty name="commentModerationMode" value="FILTERED_POSTMOD" /><feedburner:origLink>http://blog.renttalent.dk/2010/01/getting-syntaxhighlighter-to-work-with.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0YHQX49eyp7ImA9Wx5QE0k.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804.post-9214159146402437064</id><published>2009-09-18T15:24:00.018+02:00</published><updated>2010-09-01T14:45:30.063+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-09-01T14:45:30.063+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JIT" /><category scheme="http://www.blogger.com/atom/ns#" term="Compiler" /><category scheme="http://www.blogger.com/atom/ns#" term="Stack Trace" /><category scheme="http://www.blogger.com/atom/ns#" term="Inline" /><category scheme="http://www.blogger.com/atom/ns#" term="Code" /><category scheme="http://www.blogger.com/atom/ns#" term="CLR" /><title>When you can't trust the stack trace</title><content type="html">&lt;span style="color: rgb(255, 0, 0);"&gt;Disclaimer: This article is for x86 Jit compiler Only.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-size:130%;"&gt;Why did I notice that the stack trace was different from what was expected?&lt;/span&gt;&lt;br /&gt;
We have an abstract base class that our test script derive from, which provides all the necessary functionality to make the logging of data transparent for the script author. To put data into the log (database, file, whatever) the script just invoke the log method from the base class and it will then find out from where that method came from based on the information on the stack.&lt;br /&gt;
&lt;br /&gt;
The problem that I encountered was that we have some methods that only acts as proxies and thus are very small, e.i. 2-3 lines of code, with one being the call to the log method. These methods where in-lined, thus giving some strange data.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-size:130%;"&gt;When is code in-lined?&lt;/span&gt;&lt;br /&gt;
To answer when the JIT compiler does not in-line code, and thus also indicated when it might in-line code, here is an excerpt from David Notario's WebLog (&lt;a href="http://blogs.msdn.com/davidnotario/archive/2004/11/01/250398.aspx"&gt;link&lt;/a&gt;)&lt;blockquote&gt;&lt;p&gt;These are some of the reasons for which we won't inline a method:&lt;br /&gt;
&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Size of inlinee is limited to 32 bytes of IL&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Method is marked as not inline with the CompilerServices.MethodImpl attribute.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Virtual calls&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Call targets that are in MarshalByRef classes won't be inlined&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;VM restrictions&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;loops, methods with exception handling regions, etc...&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Other: Exotic IL instructions, security checks that need a method frame, etc...&lt;br /&gt;
&lt;/li&gt;
&lt;/ul&gt;&lt;/blockquote&gt;&lt;br /&gt;
&lt;span style="font-size:130%;"&gt;Why does the release build have the full call stack  in VS&lt;/span&gt;&lt;br /&gt;
If you try to debug this behavior by setting the configuration manager to "Release" and run the executable from within Visual Studio, you will notice that the stack looks just as if it was run in "Debug". This is because that VS has its own host process (vshost.exe) that starts up the CLR which tells the JIT'er not to in-line code.&lt;br /&gt;
&lt;br /&gt;
The code below gives an example on what the problem is:&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

class Program
{
 public Program()
 {
  NotInlined();
  Attribute();
  Inlined();
 }

 private void NotInlined()
 {
  try
  {return;}
  finally
  {CallerID();}
 }

 [MethodImpl(MethodImplOptions.NoInlining)]
 private void Attribute()
 {
  CallerID();
 }

 private void Inlined()
 {
  CallerID();
 }

 protected void CallerID()
 {
  StackTrace st = new StackTrace(true);
  StackFrame sf = st.GetFrame(1);
  Console.WriteLine("Caller is: " + sf.GetMethod().Name);
 }

 static void Main(string[] args)
 {
  new Program();
 }
}
&lt;/pre&gt;Running the debug and release builds from the command line the gives the following:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
output from a Debug build:&lt;br /&gt;
&lt;blockquote&gt;Caller is: NotInlined&lt;br /&gt;
Caller is: Attribute&lt;br /&gt;
Caller is: Inlined&lt;/blockquote&gt;And output from a Release build:&lt;br /&gt;
&lt;blockquote&gt;Caller is: NotInlined&lt;br /&gt;
Caller is: Attribute&lt;br /&gt;
Caller is: .ctor&lt;/blockquote&gt;&lt;img src="http://feeds.feedburner.com/~r/CodingByMyOwnExample/~4/n_e5nL6Inc4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/9214159146402437064/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://blog.renttalent.dk/2009/09/when-you-cant-trust-stack-trace.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/9214159146402437064?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/9214159146402437064?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~3/n_e5nL6Inc4/when-you-cant-trust-stack-trace.html" title="When you can't trust the stack trace" /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><thr:total>0</thr:total><gd:extendedProperty name="commentSource" value="1" /><gd:extendedProperty name="commentModerationMode" value="FILTERED_POSTMOD" /><feedburner:origLink>http://blog.renttalent.dk/2009/09/when-you-cant-trust-stack-trace.html</feedburner:origLink><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="enclosure" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~5/gprv4Knbdsg/250398.aspx" length="0" type="plain/HTML" /><feedburner:origEnclosureLink>http://blogs.msdn.com/davidnotario/archive/2004/11/01/250398.aspx</feedburner:origEnclosureLink></entry><entry gd:etag="W/&quot;DE8GQHg6fip7ImA9Wx5QE0k.&quot;"><id>tag:blogger.com,1999:blog-283325116149612804.post-6518181115176533341</id><published>2009-07-16T13:11:00.027+02:00</published><updated>2010-09-01T15:13:41.616+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-09-01T15:13:41.616+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="OpenXml" /><category scheme="http://www.blogger.com/atom/ns#" term="spreadshhet" /><category scheme="http://www.blogger.com/atom/ns#" term="datetime" /><category scheme="http://www.blogger.com/atom/ns#" term="Excel 2007" /><category scheme="http://www.blogger.com/atom/ns#" term="Code" /><title>Reading Data From OpenXML Spreadsheets</title><content type="html">During one of my assignments I had the task to read information out of a spreadsheet created with Excel 2007 (.xlsx). I choose to use the &lt;a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=C6E744E5-36E9-45F5-8D8C-331DF206E0D0&amp;amp;displaylang=en"&gt;Open XML Format SDK 2.0 (april 2009 ctp)&lt;/a&gt; to read data from the spreadsheet.&lt;br /&gt;
&lt;br /&gt;
As I Googled for the standard way of retrieving data of different type from individual cells I could not find how to interpret data from a cell with the format of "tt:mm:ss" but could not find any information on how to do it.&lt;br /&gt;
&lt;br /&gt;
So after a little debugging looking into what the different cells looked like when different types of data was put into the cells I creates a small piece of code describing what to do.&lt;br /&gt;
&lt;br /&gt;
Even though the example code doesn't look like it, every cell can have a style index, which also describes things like alignment and borders. But describing that will be a post of it's own if I even needs to figure out how to do that.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(Path, false))
{
    WorkbookPart wb = spreadsheet.WorkbookPart;
    List&amp;lt;cellformats&amp;gt; formats = new List&amp;lt;cellformats&amp;gt;(wb.WorkbookStylesPart.Stylesheet.Descendants&amp;lt;cellformats&amp;gt;());
    foreach (var sheet in wb.Workbook.Descendants&amp;lt;sheet&amp;gt;())
    {
        WorksheetPart wp = (WorksheetPart)spreadsheet.WorkbookPart.GetPartById(sheet.Id);
        SharedStringTablePart sstp = wb.GetPartsOfType&amp;lt;sharedstringtablepart&amp;gt;().First();
        SharedStringItems = sstp.SharedStringTable.Elements&amp;lt;sharedstringitem&amp;gt;().ToArray();
        foreach (var row in wp.Worksheet.Descendants&amp;lt;row&amp;gt;())
        {
            List&amp;lt;cell&amp;gt; cells = new List&amp;lt;cell&amp;gt;(row.Descendants&amp;lt;cell&amp;gt;());
            for (int i = 0; i &amp;lt; cells.Count; i++)
            {
                if (cells&amp;#91;i&amp;#93;.CellValue == null)
                {
                    // What ever to to if data is null
                }
                else
                {
                    if (cells&amp;#91;i&amp;#93;.DataType != null &amp;&amp;
                    cells&amp;#91;i&amp;#93;.DataType.HasValue &amp;&amp;
                    cells&amp;#91;i&amp;#93;.DataType.Value == CellValues.SharedString)
                    {
                        // look up the actual string value in the shared string table
                        SharedStringItem ssi = SharedStringItems&amp;#91;int.Parse(cells&amp;#91;i&amp;#93;.CellValue.Text)&amp;#93;;
                        // Do what you please with the string
                    }
                    else if (cells&amp;#91;i&amp;#93;.StyleIndex != null &amp;&amp;
                    cells&amp;#91;i&amp;#93;.StyleIndex.HasValue)
                    {
                        // look up the style used for the cell
                        int formatStyleIndex = Convert.ToInt32(cells&amp;#91;i&amp;#93;.StyleIndex.Value);
                        CellFormat cf = formats&amp;#91;0&amp;#93;.Descendants&amp;lt;cellformat&amp;gt;().ToList()&amp;#91;formatStyleIndex&amp;#93;;

                        // now you can check the NumberFormatId
                        if (cf.NumberFormatId == 21) // 21 is the “tt:mm:ss” format
                        {
                            // and the culture seem to be english-US 
                            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("EN-US");
                            // one second is
                            double second = Convert.ToDouble("1.1574074074074073E-5", ci.NumberFormat);
                            // get what’s in the cell
                            CellValue customValue = cells&amp;#91;i&amp;#93;.CellValue;
                            // convert that value to a double
                            double cellSeconds = Convert.ToDouble(customValue.InnerText, ci.NumberFormat);
                            // and calculate the total amount of seconds
                            // this is an integer to compensate for the small deviation that can occur with doubles
                            int totalSeconds = (int)(cellSeconds / second);
                            // and from that you can make a TimeSpan representing “tt:mm:ss:”
                            TimeSpan ts = new TimeSpan(0, 0, totalSeconds);
                        }
                        else if (cf.NumberFormatId == 0) // 0 seems to be just a number
                        {
                            // Do stuff
                        }
                    }
                }
            }
        }
    }
}
&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodingByMyOwnExample/~4/9QS3LKeBRR4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.renttalent.dk/feeds/6518181115176533341/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://blog.renttalent.dk/2009/07/reading-data-from-openxml-spreadsheets.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/6518181115176533341?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/283325116149612804/posts/default/6518181115176533341?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CodingByMyOwnExample/~3/9QS3LKeBRR4/reading-data-from-openxml-spreadsheets.html" title="Reading Data From OpenXML Spreadsheets" /><author><name>Morten Gejl</name><uri>https://plus.google.com/100184705726319472957</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-BAt9gCXUxJQ/AAAAAAAAAAI/AAAAAAAAAAA/fb8Ft1usjMk/s512-c/photo.jpg" /></author><thr:total>0</thr:total><gd:extendedProperty name="commentSource" value="1" /><gd:extendedProperty name="commentModerationMode" value="FILTERED_POSTMOD" /><feedburner:origLink>http://blog.renttalent.dk/2009/07/reading-data-from-openxml-spreadsheets.html</feedburner:origLink></entry></feed>
