title: .NET: Which Exception to Throw When Required Property is Not Set?
body: <p>Assume I have a class like this:</p>
  
  <pre><code>public class Foo
  {
      public Bar RequiredProperty { get; set;}
  
      public void Baz()
      {
          if (this.RequiredProperty == null)
          {
              // Which exception should I throw?
          }
      }
  }
  </code></pre>
  
  <p>My solution has a class that is designed to be reused without having to pass a lot of arguments to the <code>Bar</code> method over and over again. So, what should I throw when <code>Bar</code> isn't initialized to a non-null value?</p>
  
  <p><b>More Information</b>
  I'm essentially rolling my own code parser and formatter. Call it an object lesson. One of the classes is an <code>HtmlCodeFormatter</code> that has the following properties (in honor of Dependency Injection):</p>
  
  <pre><code>public IFormatter Formatter { get; set; }
  public IParser Parsre { get; set; }
  </code></pre>
  
  <p>This allows me to write any number of language-specific parsers and formatters. For example, I have a <code>CSharpParser</code> and a <code>JavascriptParser</code>. I also have an <code>HtmlCodeFormatter</code>, and there are plans for another (of dubious utility).</p>
  
  <p>The idea is that you can instantiate the <code>HtmlFormatter</code> using an object initializer, like this:</p>
  
  <pre><code>var formatter = new HtmlCodeFormatter()
      {
          Parser = new CSharpParser();
          Formatter = new HtmlCodeFormatter();
      };
  formatter.Format("Console.WriteLine(\"Hello, world!\"));
  </code></pre>
  
  <p>When <code>HtmlCodeFormatter.Format</code> is invoked, it needs to be able to verify that both a parser and a formatter have been provided. That's no problem, really, but I'm kind of stumped about which exception to throw. I'm leaning towards <code>InvalidOperationException</code>, but I'm not entirely certain that's the best choice.</p>