1
public void FooBar(String _connectionString, Decimal p_Query_Type, DateTime? p_Date_Start = new DateTime(2006, 1, 1), DateTime? p_Date_End, Decimal? p_Number = null, Decimal? p_Group_Id = null)

Visual Studio doesn't like how I initialized p_Date_Start

how do I set a value if the developer using my API doesn't need a value to p_Date_Start?

Error from Visual Studio

Error CS1736 Default parameter value for 'p_Date_Start' must be a compile-time constant

software is fun
  • 7,286
  • 18
  • 71
  • 129

3 Answers3

2

Default parameter for value must be a compile time constant. Dynamically calculated value is not accepted by compiler against optional parameter.

Let's say as anlternative DateTime? = null; and in method,

var effective_p_Date_Start = p_Date_Start ?? new DateTime(2006, 1, 1)

If necessary, you can follow up the way for others.

0

roughly like this:

in methodhead use

DateTime? p_Date_Start = null

and in the method:

p_Date_Start ??= new DateTime(2006, 1, 1)

also I should mention that DateTime? p_Date_End also needs a default since all optional parameters must come at last

Patrick Beynio
  • 788
  • 1
  • 6
  • 13
0

You can use null as the default value, and then handle the null case in the method body:

public void FooBar(String _connectionString, Decimal p_Query_Type, DateTime? p_Date_Start = null, DateTime? p_Date_End, Decimal? p_Number = null, Decimal? p_Group_Id = null)
{
  if (p_Date_Start == null) p_Date_Start = new DateTime(2006, 1, 1);
  // more stuff here
}
mmathis
  • 1,610
  • 18
  • 29