title: Is it possible to have an optional parameter be an object in C#?
body: <p>For example, let's say I want to create a function like so, and want the last argument to be optional (if supplied, use it - otherwise just create a new one and use that)</p>
  <pre><code>public void DoSomething (int x, int y = 5, Search search = new Search())
  {
  ...
  }
  </code></pre>
  <p>I get the error:</p>
  <blockquote>
  <p>&quot;Default parameter value for 'search' must be a compile-time constant&quot;</p>
  </blockquote>
  <p>So I tried making the initial value constant or just creating a class member, but that doesn't seem to work either:</p>
  <pre><code>private const Search DefaultSearch = new Search();
  //OR
  private Search DefaultSearch;
  public MyClassConstructor()
  {
     DefaultSearch = new Search();
  }
  ...
  public void DoSomething (int x, int y = 5, Search search = DefaultSearch)
  {
  ...
  }
  
  </code></pre>
  <p>But neither of those worked either due to errors. I also tried making the type Search nullable with a ? but I guess that isn't allowed in my version of C# (7.3). Any solutions? I don't want to give up and just use an overloaded method, if possible. A coworker mentioned delegates might accomplish this, but I've never used one and can't figure out the syntax to make it work in this instance.</p>