I've read both
Optional parameters "must be a compile-time constant"
And
Default parameter for value must be a compile time constant?
But this keeps not compiling on the declaration, marking Empty
as a non constant.
public class MyClass
{
private const string Empty = string.Empty;
private string WriteFailedList(string prefix = Empty, DeployResponse Ret)
{
StringBuilder sb = new StringBuilder();
var errorItems = Ret.Items.TakeWhile(item => item.Status == DeployItem.ItemStatus.Error);
foreach (var item in errorItems)
sb.AppendLine(string.Format("{0} {1}",prefix,item.Filename));
return sb.ToString();
}
}
@Edit: Code good practice suggestions taken from Jon Skeet.
The code you've given has two problems:
params
parameters)const
fields must be assigned compile-time constants, and string.Empty
isn't a const fieldEmpty
isn't a valid const
, your default value isn't const
. This is just a corollary of the second issueBoth of these are easily fixed:
private const string Empty = ""; // Literal rather than String.Empty
...
// Parameter name changed to be more readable and conventional
private string WriteFailedList(DeployResponse response, string prefix = Empty)
{
...
}
Or get rid of your own Empty
constant:
private string WriteFailedList(DeployResponse response, string prefix = "")
{
...
}
(I'd also advise you to use camelCase
for your parameters and local variables - so errorItems
rather than ErrorItems
. Or just errors
, in fact. I'd also use a foreach
loop instead of calling ToList()
and then using ForEach
.)
See more on this question at Stackoverflow