error CS0150:A constant value is expected //error in switch statement
case
can only be used with a constant. It should either be
private const string multi = "multi";
switch (caseslol)
{
case multi:
Console.WriteLine(e * b);
// you also need this
break;
}
or you do directly
switch (caseslol)
{
case "multi":
Console.WriteLine(e * b);
// you also need this
break;
}
or you simply use
if(string.Equals(caseslol, multi))
{
Console.WriteLine(e * b);
}
in general I don't see where caseslol
ever gets set ...
C# A constant value is expected when trying to compare two integers in switch case
You would have to use an if
statement to accomplish what you want, or make int2
const
.
Tutorials Point does a good job of explaining this:
The following rules apply to a switch statement −
The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, then it will raise a compile time error.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true.
switch statement in C# and a constant value is expected
Properties.Settings.Default.OU_HomeOffice
isn't a constant string - something known at compile time. The C# switch statement requires that every case is a compile-time constant.
(Apart from anything else, that's the only way it can know that there won't be any duplicates.)
See section 8.7.2 of the C# 3.0 spec for more details.
switch statement: a constant value is expected
With the new pattern matching feature of C# 7 I would solve it in the following manner.
Here a simple Field
and Document
class
public class Field
{
public string Label { get; set; }
}
public class Field<T> : Field
{
public T Value { get; set; }
}
public class Document
{
public string Content { get; set; }
}
And here a FieldOperator
class which does some arbitrary changes to a list of Field
s
public static class FieldOperator
{
public static void Operate(Field[] fields)
{
foreach (var field in fields)
{
field.Label = field.GetType().ToString();
switch (field)
{
case Field<Document> docField:
docField.Value.Content = "Foo Bar";
break;
case Field<int> intField:
intField.Value = 600842;
break;
default:
field.Label = "Oops";
break;
}
}
}
}
Testing for correctness of these "operations"
[Test]
public void OperationsAreCorrect()
{
var docField = new Field<Document> {Value = new Document {Content = "Hello World"}};
var intField = new Field<int> {Value = 17};
var dateField = new Field<DateTime>();
FieldOperator.Operate(new Field[] {docField, intField, dateField});
Assert.IsTrue(docField.Label == docField.GetType().ToString());
Assert.IsTrue(intField.Label == intField.GetType().ToString());
Assert.IsTrue(dateField.Label == "Oops");
Assert.IsTrue(docField.Value.Content == "Foo Bar");
Assert.IsTrue(intField.Value == 600842);
Assert.IsTrue(dateField.Value == default(DateTime));
}
A constant value is expected
You should do this with if / else.
However, if for some reason you really want to use a switch, you can sort of do it with pattern maching.
e.g.
void Main()
{
string[] words = {"Foo", "Bar", "Quax"};
var word = "Bar";
switch(word)
{
case string w when w == words[0]:
MessageBox.Show($"word was {words[0]}");
break;
case string w when w == words[1]:
MessageBox.Show($"word was {words[1]}");
break;
}
}
Really though, use if / else here. I don't think switch is appropriate for this type of use case.
In C#, How To Perform Pattern Matching With Switch For Non-Constant String Value?
No need to introduce a variable (as in your answer) - you can use discard with case guard:
public bool UseStandardSwitch(string inputValue)
{
var expectedValue = Console.ReadLine()!;
Func<bool> DoSomething = () => true;
return inputValue switch
{
_ when inputValue.Equals(expectedValue) => DoSomething(),
_ when inputValue.Equals(expectedValue + "1") => DoSomething(),
_ => throw new ArgumentException(),
};
}
Related Topics
No Console Output When Using Allocconsole and Target Architecture X86
Identityserver4 Role Based Authorization for Web API with ASP.NET Core Identity
Ews - Access All Shared Calendars
Why Func<T,Bool> Instead of Predicate<T>
Convert Bitmaps to One Multipage Tiff Image in .Net 2.0
Linq Expression to Return Property Value
What Is the Fastest Way to Combine Two Xml Files into One
Winforms | C# | Autocomplete in the Middle of a Textbox
Windows 7 and Vista Uac - Programmatically Requesting Elevation in C#
What Is the Static Variable Initialization Order Across Classes in C#
Arbitrary-Precision Decimals in C#
What's the Difference Between Iequatable and Just Overriding Object.Equals()
Does Using Tasks (Tpl) Library Make an Application Multithreaded
How to Find Out If a File Exists in C#/.Net
C# How to Wait for a Webpage to Finish Loading Before Continuing