1

The C# code below is giving me error on the two lines beginning with case . The error is "A constant value is expected"

The VB.NET code below is working. I'm using this code as a sample for my real app written in C#.

I don't see the problem but that doesn't mean one isn't present. I used a couple of online code converters to double-check the syntax. Both are returning the same result, which gives the error.

ExportFormatType is an enum in a third-party library.

Any suggestions? Thanks!

public void ExportCrystalReport(string exportType, string filePath)
    {
        if (_CReportDoc.IsLoaded == true)
        {
            switch (exportType)
            {
                case  ExportFormatType.PortableDocFormat.ToString():  // Or "PDF"
                    ExportTOFile(filePath, ExportFormatType.PortableDocFormat);
                    break;
                case ExportFormatType.CharacterSeparatedValues.ToString(): // Or "CSV"
                    ExportTOFileCSV(filePath, ExportFormatType.CharacterSeparatedValues);

                    break;
            }
        }


 Public Sub ExportCrystalReport(ByVal exportType As String, ByVal filePath As String)

        If _CReportDoc.IsLoaded = True Then
            Select Case exportType
                Case ExportFormatType.PortableDocFormat.ToString 'Or "PDF"
                    ExportTOFile(filePath, ExportFormatType.PortableDocFormat)
                Case ExportFormatType.CharacterSeparatedValues.ToString ' Or "CSV"
                    ExportTOFileCSV(filePath, ExportFormatType.CharacterSeparatedValues)

1 Answer 1

5

In C#, case statement labels must be values known at compile time. I don't believe this same restriction holds true for VB.NET.

In principle, ToString() can run arbitrary code, so it's value is not known at compile time (even though in your case it is an enum).

To address this you can either first parse the exportType into a enum, and switch on the enum value in C#:

ExportFormatType exportTypeValue = Enum.Parse(typeof(ExportFormatType), exportType);
switch( exportTypeValue )
{
    case ExportFormatType.PortableDocFormat: // etc...

or you could convert the switch to an if/else statement:

if( exportType == ExportFormatType.PortableDocFormat.ToString() )
   // etc...
Sign up to request clarification or add additional context in comments.

2 Comments

Probably should use Enum.TryParse here, to handle the case where the string passed in isn't one of the named constants defined for the enumeration.
@JimL Good point. And along those lines, a default case is also usually a good idea when dealing with arbitrary input switch statements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.