title: Casting string in SSIS script task for for loop in C#
body: <p>I've just spent well over an hour finding a solution to a problem - now I'm curious as to why it works.  I was getting this error in SSIS when I executed a package:</p>
  
  <p><img src="https://i.stack.imgur.com/uqviW.jpg" alt="enter image description here"></p>
  
  <p>I had a script task which was accessing a variable.  I'd correctly added this to the ReadOnlyVariables collection for the script task, and was confident I'd used the right case.  Here was my script line which wasn't working:</p>
  
  <pre><code>string textToWrite = (string)Dts.Variables["User::TestNumber"].Value;
  </code></pre>
  
  <p>Eventually I changed this to:</p>
  
  <pre><code>string textToWrite = Dts.Variables["User::TestNumber"].Value.ToString();
  </code></pre>
  
  <p>and everything worked OK.  My question is: why did this fail before?</p>