Switch case in C# - a constant value is expected
See C# switch statement limitations - why?
Basically Switches cannot have evaluated statements in the case statement. They must be statically evaluated.
You can only match to constants in switch statements.
Example:
switch (variable1)
{
case 1: // A hard-coded value
// Code
break;
default:
// Code
break;
}
Successful!
switch (variable1)
{
case variable2:
// Code
break;
default:
// Code
break;
}
CS0150 A constant value is expected.
Now you can use nameof
:
public static void Output<T>(IEnumerable<T> dataSource) where T : class
{
string dataSourceName = typeof(T).Name;
switch (dataSourceName)
{
case nameof(CustomerDetails):
var t = 123;
break;
default:
Console.WriteLine("Test");
}
}
nameof(CustomerDetails)
is basically identical to the string literal "CustomerDetails"
, but with a compile-time check that it refers to some symbol (to prevent a typo).
nameof
appeared in C# 6.0, so after this question was asked.
There is this trick which was shared with me (don't ask for details - won't be able to provide them, but it works for me):
switch (variable_1)
{
case var value when value == variable_2: // that's the trick
DoSomething();
break;
default:
DoSomethingElse();
break;
}
You can't use a switch statement for this as the case values cannot be evaluated expressions. For this you have to use an an if/else ...
public static void Output<T>(IEnumerable<T> dataSource) where T : class
{
dataSourceName = (typeof(T).Name);
if(string.Compare(dataSourceName, typeof(CustomerDetails).Name.ToString(), true)==0)
{
var t = 123;
}
else if (/*case 2 conditional*/)
{
//blah
}
else
{
//default case
Console.WriteLine("Test");
}
}
I also took the liberty of tidying up your conditional statement. There is no need to cast to string after calling ToString()
. This will always return a string anyway. When comparing strings for equality, bare in mind that using the == operator will result in a case sensitive comparison. Better to use string compare = 0 with the last argument to set case sensitive on/off.