title: Enums And WCF - Meaningful Error?
body: <p>I'm trying to overcome a problem with WCF and enums, where I'm trying to pass an object from the server to the client (or another server), which contains an enum. The enum starts with 1, on purpose. Everything goes fine when the enum is initialized and when the value is defined in it, but when it's not defined in the enum, I get this wonderful (and very descriptive(...)) error message:</p>
  
  <p>"The underlying connection was closed: The connection was closed unexpectedly."</p>
  
  <p>What I try to achieve is when I get this scenario, either from corrupted data in the database (which is being casted anyway to the enum, which is pretty wierd altogether) or when a developer forgot to set the enum value when initiating the object, to get a meaningful message, something like "Enum value is not valid, type: {0}, value: {1}".</p>
  
  <p>I've tried to use the "Enum.IsDefined" on the setter and getter of the enum in the class, and throw the meaningful exception to the client (or the other server), but still got the "connection close" error (when allowing to debug the server I get the meaningful message but on the server side only).</p>
  
  <p>Here's a snippet of the enum setter &amp; getter:</p>
  
  <pre><code>    private TestEnum m_TestEnum;
  
      [DataMember]
      public TestEnum TestEnum 
      {
          get
          {
              if (Enum.IsDefined(typeof(TestEnum), m_TestEnum))
              {
                  return m_TestEnum;
              }
              else
              {
                  throw new ApplicationException("Enum value is not valid: " + m_TestEnum);
              }
          }
          set
          {
              if (Enum.IsDefined(typeof(TestEnum), value))
              {
                  m_TestEnum = value;
              }
              else
              {
                  throw new ApplicationException("Enum value is not valid: " + value);
              }
          }
      }
  </code></pre>
  
  <p>Starting the enum from 0 (with an "Unknown" value) is not a good enough, since I can still get values which don't exist in the enum. I can combine both solutions, where I check the "IsDefined" and set the enum to the "Unknown" value, but still - this is not the ideal solution, since we want to know about those cases in order to solve them in development cycle.</p>
  
  <p>What do you say?
  Thanks,
  Nir.</p>