title: Access Dictionary Items in Data Property of Exception Class
body: <p>I'm having difficulty accessing the values of the data property of the Exception class.</p>
  
  <pre><code>try
  {
      string strReasonCode = String.Empty;
      string strReasonDescription = String.Empty;
      string strDuration = String.Empty;
      string strActive = String.Empty;
  
      if (ReasonCodeDT.Rows.Count != 1)
      {
          string strPracticeID = PracticeID.ToString();
          string PracticeName = getSingleStringResultFromSQL("SELECT @result = PracticeName FROM Practice WHERE PracticeID = /'" + strPracticeID + "/'"); 
          string RecordCount = ReasonCodeDT.Rows.Count.ToString();
          int UserID;
          Int32.TryParse(au.UserID, out UserID);
          Exception ex = new Exception("Database Returned " + RecordCount + " Records for ReasonCodeID " + ReasonCodeID + " for Practice " + PracticeName + " (" + strPracticeID + ")");
          ex.Data.Add("UI Error Message", "Whoops! Something went wrong there. Please call (555)555-5555" +
              "and notify them something is wrong with the Encounter Reason: " + ReasonCodeID);
          throw ex;
      }
      else
      {
      }
  }
  catch
  {
      pnlError.Visible = true;
      lblErrorMessage.Text = ex.Data["UI Error Message"];
  }
  </code></pre>
  
  <p>This gives me a compiler error message:</p>
  
  <blockquote>
    <p>Error 117 Cannot implicitly convert type 'object' to 'string'. An
    explicit conversion exists (are you missing a cast?)</p>
  </blockquote>
  
  <p>All the references I can find access that information by using <code>foreach</code> loops specifying the type as <code>DictionaryEntry</code> but that isn't necessary/ desirable for this instance:</p>
  
  <ul>
  <li><p><a href="https://msdn.microsoft.com/en-us/library/system.exception.data(v=vs.110).aspx?cs-save-lang=1&amp;cs-lang=csharp#code-snippet-2" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/system.exception.data(v=vs.110).aspx?cs-save-lang=1&amp;cs-lang=csharp#code-snippet-2</a></p></li>
  <li><p><a href="https://www.dotnetperls.com/exception" rel="nofollow noreferrer">https://www.dotnetperls.com/exception</a></p></li>
  </ul>
  
  <p>How do I retrieve a single item from that dictionary? </p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>In reference to @dbc's suggestion of creating a custom exception class, here is a link providing more detail as to why I didn't do so.</p>
  
  <p><a href="https://blogs.msdn.microsoft.com/jaredpar/2008/10/20/custom-exceptions-when-should-you-create-them/" rel="nofollow noreferrer">https://blogs.msdn.microsoft.com/jaredpar/2008/10/20/custom-exceptions-when-should-you-create-them/</a></p>
  
  <p>Feel free to comment as to why an exception class would be better than using the data property of the base exception class.</p>