3

The answer for C# 4.0 doesn't work anymore. <-- (Sorry, this is wrong)

How can I use a TimeSpan as an optional parameter with default value?

public static Foo(string myString, TimeSpan maxWait = TimeSpan.FromSeconds(1))
{
    // do something
}

With this code I get the error:

default parameter must be a compile-time constant

kame
  • 19,003
  • 30
  • 100
  • 149
  • 1
    What do you mean by "the answer for C# 4 doesn't work anymore"? – Evk Apr 13 '17 at 08:26
  • @EvK I missed one `?` from an other SO example. Therefore it didn't work. :/ Therefore I close this post. – kame Apr 13 '17 at 08:30

1 Answers1

11

This has never worked in any C# version. Defaults must be constants. You have to create an overload to default the value, or make it nullable and default it if the value is null.

Option 1:

public static Foo(string myString)
{
    Foo(myString, TimeSpan.FromSeconds(1));
}

public static Foo(string myString, TimeSpan maxWait)
{
    // do something
}

Option 2:

public static Foo(string myString, TimeSpan? maxWait = null)
{
    TimeSpan maxWaitNotNull = maxWait ?? TimeSpan.FromSeconds(1);
    // do something
}
Evk
  • 90,493
  • 8
  • 125
  • 177
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306