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
  • 20,848
  • 33
  • 104
  • 159
  • 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

13

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
  • 98,527
  • 8
  • 141
  • 191
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325