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

5
  • try to declare your 2006, 1, and 1 as a static value Commented Mar 13, 2020 at 13:00
  • 1
    @Lotan Only consts can be used as default values, so that won't help Commented Mar 13, 2020 at 13:01
  • Default the datetime to null, DateTime? p_Date_Start = null, then at the beginning of your method do p_Date_Start ??= new DateTime(2006, 1, 1) Commented Mar 13, 2020 at 13:01
  • I would just write two overloads to be honest... Commented Mar 13, 2020 at 13:01
  • @canton7 you're right :( Commented Mar 13, 2020 at 13:05

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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 } 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.