0

Simple question. Is it possible to invoke a method within a switch statement in C#? Asking for .NET >= 4.5

var x = "Hello World";
switch(x)
{
    case "Foo":
        break;
    // What I actually want to do
    case x.StartsWith("Hello"):
        return "Bar";
}
boop
  • 7,413
  • 13
  • 50
  • 94

1 Answers1

7

No. case has to be followed by compile time constant, and method call is definitely not one of them.

Part of C# grammar from C# spec:

switch-statement:
    switch   (   expression   )   switch-block

switch-block:
{   switch-sectionsopt   }

switch-sections:
    switch-section
    switch-sections   switch-section

switch-section:
    switch-labels   statement-list

switch-labels:
    switch-label
    switch-labels   switch-label

switch-label:
    case   constant-expression   :
    default   :

As you can see, case has to be followed by constant-expression, which is described as

A constant-expression is an expression that can be fully evaluated at compile-time.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263