I have the following class of Schedule and using .Net Framework 4.0.
this class has two constructors, both having the parameter of interval with a default value of 120 seconds. is there any way to set the default value of interval in a private variable and then assign that variable to interval parameter. I tried doing it, but I get a compile time error saying Default parameter value for 'interval' must be a compile-time constant
public class Schedule
{
public Delegate Callback { get; set; }
public object[] Params { get; set; }
public int Interval { get; set; }
public Schedule(Delegate callback, int interval = 120)
{
}
public Schedule(Delegate callback, object[] parameters, int interval = 120)
{
}
}
No, because the way that optional parameters work is that the compiler of the calling code has the default value baked into it. So a call like this:
is converted at compile-time into:
So that’s why it has to be a constant. Now, you can still make that a constant – even a private one, if you want – but it can’t be a normal variable. So this would be okay:
If you want a value which may vary at execution time, you could use a nullable type as the parameter, with the null value being the default, replaced by the real default at execution time. For example, here’s a method which allows you to specify a timestamp, but defaults to “now”: