1

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.

Community
  • 1
  • 1
apacay
  • 1,702
  • 5
  • 19
  • 41
  • That code doesn't give me that error - it gives me "Optional parameters must appear after all required parameters". – Jon Skeet Jun 10 '14 at 15:29
  • Awkward, I'll do that to see if it vanishes. – apacay Jun 10 '14 at 15:30
  • possible duplicate of [Why can't I use string.Empty as an optional parameter contrary to empty quotation marks?](http://stackoverflow.com/questions/23984972/why-cant-i-use-string-empty-as-an-optional-parameter-contrary-to-empty-quotatio) – Jeroen Vannevel Jun 11 '14 at 12:09

1 Answers1

2

The code you've given has two problems:

  • Optional parameters must come last (apart from params parameters)
  • const fields must be assigned compile-time constants, and string.Empty isn't a const field
  • Because Empty isn't a valid const, your default value isn't const. This is just a corollary of the second issue

Both 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.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I was just thinking on this, when I changed the order as you suggested, string.Empty yelled at me that it wasn't a constant. Seems that the error came from .net "noncompiled" code suggestions. – apacay Jun 10 '14 at 15:35