-2

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)

public void DoSomething (int x, int y = 5, Search search = new Search())
{
...
}

I get the error:

"Default parameter value for 'search' must be a compile-time constant"

So I tried making the initial value constant or just creating a class member, but that doesn't seem to work either:

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)
{
...
}

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.

iaacp
  • 4,655
  • 12
  • 34
  • 39

1 Answers1

1

The only thing you can do is something similiar to this:

/// <summary>
/// Does something.
/// </summary>
/// <param name="search">The search. If null it is by default <see cref="DefaultSearch"/>.</param>
//public void DoSomething (int x, int y = 5, Search? search = null)
public void DoSomething (int x, int y = 5, Search search = null)
{
  //search ??= DefaultSearch;
  search = search ?? DefaultSearch;
}
Teneko
  • 1,417
  • 9
  • 16