How can I avoid the need to cast to (ServiceException) in the following code?
<p>I created an exception class like this:</p>

<pre><code>public class ServiceException : ApplicationException {

    public Dictionary&lt;string, string&gt; Errors { get; set; }

    public ServiceException(Exception ex) : base("Service Exception", ex) {
      Errors = new Dictionary&lt;string, string&gt;();
    }
    public ServiceException() : this(null) {}

}
</code></pre>

<p>The following code fails:</p>

<pre><code>protected void log(Exception ex)
{
    if (ex is ServiceException)
    {
        var y = (ServiceException)
        ModelState.Merge(ex.Errors);
    }
    else
    {
        Trace.Write(ex);
        ModelState.AddModelError("", "Database access error: " + ex.Message);
    }
}
</code></pre>

<p>It generates the following error on compile:</p>

<blockquote>
  <p>Error 5 'System.Exception' does not contain a definition for 'Errors'
  and no extension method 'Errors' accepting a first argument of type
  'System.Exception' could be found (are you missing a using directive
  or an assembly reference?)</p>
</blockquote>

<p>I fixed it by doing the following: </p>

<pre><code>if (ex is ServiceException)
{
    var y = (ServiceException)ex;
    ModelState.Merge(y.Errors);
}
</code></pre>

<p>Is there some way that I can avoid this messy code using a variable y and then casting it ? Without declaring the intermediate variable y the code does not pass a syntax check.</p>
