| public void DoStuff(TimeSpan interval = TimeSpan.FromSeconds(5)) |
The compiler error is: "Error 1 Default parameter value for 'interval' must be a compile-time constant".
I have tried making a const field in the class but still no luck.
| public void DoStuff(TimeSpan interval = TimeSpan.FromSeconds(5)) |
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Apr 2, 2012, 11:34 AM
So, the memory location for TimeSpan.Zero actually contains an 8 byte value - it doesn't contain a reference (i.e. a pointer) to where an instance is stored on the heap which would be the case if TimeSpan were a class rather than a struct.
By always calling TimeSpan.Zero, you're re-using the value stored at its memory location. This value will persist throughout the application's lifetime and will never be garbage collected.
time and spacePosted Apr 2, 2012, 11:17 AM
VulpesPosted Apr 2, 2012, 11:08 AM
You'd just be copying the values to another location and it would be no shorter to write.
time and spacePosted Apr 2, 2012, 9:33 AM
VulpesPosted Apr 2, 2012, 9:25 AM
I think that it uses a long integer (8 bytes) to represent TimeSpan values internally, so TimeSpan.Zero will be repesented by a long with a value of 0.
TimeSpan.Zero is a static readonly field which creates a single TimeSpan instance. The same instance is used each time the field is accessed.
Vector2 is also a struct though for some reason Vector2.Zero is a static readonly property rather than a field.
time and spacePosted Apr 2, 2012, 9:11 AM
time and spacePosted Jul 28, 2011, 11:34 PM
VulpesPosted Jul 25, 2011, 9:24 AM
This works because default(TimeSpan) sets all bits to zero and so is equivalent to TimeSpan.Zero. However, the former is regarded as a constant but the latter is not.
VulpesPosted Jul 25, 2011, 8:51 AM
Guest UserPosted Jul 25, 2011, 8:38 AM
Zoran HorvatPosted Jul 25, 2011, 7:52 AM
Benjamin KemnerPosted Jul 25, 2011, 7:51 AM
public void DoStuff(int initvalue=5){
TimeSpan interval = TimeSpan.FromSeconds(initvalue);
}
Or the "old-school" way:
public void DoStuff(){
DoStuff(TimeSpan.FromSeconds(5));
}
public void DoStuff(TimeSpan interval){
}
Zoran HorvatPosted Jul 25, 2011, 7:40 AM
Do not use TimeSpan as argument but integer which receives seconds, then declare the method like this:
public void DoStuff(int seconds=5)
{
TimeSpan interval = TimeSpan.FromSeconds(seconds);
...
}
Second solution:
Do it old style C# - define two methods, one receiving interval, another without arguments:
public void DoStuff(TimeSpan interval)
{
...
}
public void DoStuff()
{
DoStuff(TmeSpan.FromSeconds(5));
}
Zoran