title: Converting C# Data Types from unknown sources
body: <p>There seems to be a lot of confusion around converting strings (usually) to their appropriate datatype, whilst validating it on the fly as well. Wherever I look - blogs, articles, code samples, forums.. a few people seem to have a <strong><em>preferred</em></strong> way of dealing with these scenarios. </p>
  
  <p>The case is usually a string/object that comes from an unknown source, such as QueryString, Session/Viewstate, WebService, and so on...</p>
  
  <p><strong>I've seen many different examples:</strong></p>
  
  <p>Say we're trying to get the <code>id=</code> Query String and use it in our code as an integer. But someone tampered with our URL and changed it to</p>
  
  <blockquote>
    <p><a href="http://www.example.com/page.aspx?id=sometextvalue" rel="nofollow">http://www.example.com/page.aspx?id=sometextvalue</a></p>
  </blockquote>
  
  <p><strong>One way</strong></p>
  
  <pre><code>int id = Convert.ToInt32(Request["id"]);
  // "Input string was not in a correct format"
  </code></pre>
  
  <p><strong>Another way</strong></p>
  
  <pre><code>int id = (int)Request["id"];
  // "Input string was not in a correct format"
  </code></pre>
  
  <p><strong>Yet another way</strong></p>
  
  <pre><code>int id = int.Parse(Request["id"]);
  // "Input string was not in a correct format"
  </code></pre>
  
  <p><strong>I have ever seen this</strong> <em>(And it kind of makes sense to throw an exception and notify the user)</em></p>
  
  <pre><code>int id = 0;
  try {
      id = Convert.ToInt32(Request["id"]);
  }
  catch(Exception ex) {
      lblError.Text = ex.Message;
  }
  if(id &gt; 0) { ... }
  </code></pre>
  
  <p><strong>Lastly, and the one I personally use</strong></p>
  
  <pre><code>int id = 0;
  int.TryParse(Request["id"], out id);
  
  // make sure it's not 0
  if(id &gt; 0) { // live a happy life }
  </code></pre>
  
  <p>This goes for all the other types, <code>bool</code>, <code>double</code>, <code>decimal</code> and so on..</p>
  
  <p>Please help me understand what the correct way is, as I find myself using this on a day-to-day basis.</p>