title: Bypassing C#'s type safeguards and storing an Integer in a String
body: <p>Have a look at the following code:</p>
  
  <pre><code>static void Main(string[] args)
  {
      string s = null;
      string[] myArray = new string[1];
  
      { } // do something evil here
  
      if (s.GetType() == typeof(int))
      {
          Console.WriteLine("This should not happen!"); 
      }
      Console.ReadLine();
  }
  </code></pre>
  
  <p>Is there any way to get <code>This should not happen</code> to write? One would assume not. However, it can be done with the debugger: Put a breakpoint into the line <code>{ } // do something evil here</code> and execute the following commands in the Immediate Window before continuing:</p>
  
  <pre><code>((object[])myArray)[0] = 99;
  s = myArray[0];
  </code></pre>
  
  <p>Execution continues and <code>This should not happen</code> will be printed. Tested with Visual Studio 2008; here is a screenshot:</p>
  
  <p><img src="https://i.stack.imgur.com/4N67R.png" alt="screenshot"></p>
  
  <p>Is this kind of trickery only possible with the debugger or is there some way to do such an "unsafe assignment" in code?</p>
  
  <p>(Obviously, I ask only out of scientific curiosity. <a href="https://stackoverflow.com/q/17640882/87698">This question</a> and the related comments made me ask this question.)</p>