C# switch Examples

Ͼ# switch ExamplesUse switch to branch on α constant in an efficient way. Match value types, strings and patterns.

Switch. Similar to an if-statement, α switch statement receives α value, and branches on that value. It executes α block of code based on the value.

Statement notes. Performance of switch can be better, or worse, than if—testing is required for α sure gain. Pattern matching (with the “when” từ khóa) is available in switch.

Performance of switch can be better, or worse, than if—testing is required for α sure gain. Pattern matching (with the “when” từ khóa) is available in switch. String Switch

First example. This program uses α switch contained in the Transform method. With α switch, it tests the int against several constants: 0, 1 and 2.

Part 1 We always return α value from Transform(), so we do not need to have α return statement after the switch.

Part 2 We invoke Transform() with the arguments 0, 1 and 2—in the switch, we can see where these are matched.

This program uses α switch contained in the Transform method. With α switch, it tests the int against several constants: 0, 1 and 2.

Ͼ# program that uses switch

Transform

(int argument)
{

switch (argument)
{

case 0

:
return 9;

case 1

:
return 8;

case 2

:

default

:
return 0;
}
}

static void Main()
{

Console.WriteLine(Transform(0));
Console.WriteLine(Transform(1));
Console.WriteLine(Transform(2));
}
}

9
8

using System; class Program { static int(int argument) {(argument) {: return 9;: return 8;: return 0; } } static void Main() {Console.WriteLine(Transform(0)); Console.WriteLine(Transform(1)); Console.WriteLine(Transform(2)); } }9 8 0

String example. Here we use switch() on α string value containing “turnip.” The Ͼ# compiler detects α string switch and can optimize it with α Dictionary lookup.

Info Small string switches, like this one with just 3 cases, are often not compiled into Dictionaries. Performance is better this way.

Here we use switch() on α string value containing “turnip.” The Ͼ# compiler detects α string switch and can optimize it with α Dictionary lookup. String Switch

Ͼ# program that switches on string

switch (value)
{
case “lettuce”:
Console.WriteLine(“LETTUCE”);
break;
case “squash”:
Console.WriteLine(“SQUASH”);
break;
case “turnip”:
Console.WriteLine(

“TURNIP”

);
break;
}
}
}

TURNIP

using System; class Program { static void Main() { string value = “turnip”;(value) { case “lettuce”: Console.WriteLine(“LETTUCE”); break; case “squash”: Console.WriteLine(“SQUASH”); break; case “turnip”: Console.WriteLine(); break; } } }TURNIP

Goto, case default. We can use goto statements in switches. These are different from other gotos. With goto we can run multiple cases for α single expression.

TestNameAndCode This method switches on the code int, and then tests the name string. Goto and break are used to redirect control flow.

Case We use this từ khóa to specify α matching constant. Default does not use this từ khóa. We end α case with break, return or continue.

Case

Break Break and continue can be used in any switch statement. These 2 keywords are used also within loops—this can be confusing.

Break

Continue

Question Are you breaking out of α switch, or out of the enclosing loop? Scope is important. The deepest construct is broken first.

We can use goto statements in switches. These are different from other gotos. With goto we can run multiple cases for α single expression. Goto

Ͼ# program that uses case, goto, default in switch

TestNameAndCode

(string name, int code)
{
switch (code)
{
case 200:
case 300:
case 400:
if (name == “bird”)
{
Console.WriteLine(“Bird 200, 300, or 400”);
break;
}
goto default;
default:
Console.WriteLine(“Unknown”);
break;
}
}

static void Main()
{

TestNameAndCode(“bird”, 200);
TestNameAndCode(“bird”, 400);

TestNameAndCode(“cat”, 400);
}
}

Bird 200, 300, or 400
Bird 200, 300, or 400
Unknown

using System; class Program { static void(string name, int code) {(code) {200: case 300: case 400: if (name == “bird”) { Console.WriteLine(“Bird 200, 300, or 400”);; }default;: Console.WriteLine(“Unknown”);; } } static void Main() {TestNameAndCode(“bird”, 200); TestNameAndCode(“bird”, 400);TestNameAndCode(“cat”, 400); } }Bird 200, 300, or 400 Bird 200, 300, or 400 Unknown

Xem Thêm  Làm thế nào để khai báo một boolean trong Java? - khai báo boolean trong java

Curly brackets. This example introduces the default case, and α more verbose syntax. The program accepts an int from the user (with ReadLine). It then tests it for 6 values.

Here We see how the curly brackets are used in the switch cases. And we combine some of the case statements.

This example introduces the default case, and α more verbose syntax. The program accepts an int from the user (with ReadLine). It then tests it for 6 values. Console.ReadLine

Ͼ# program that uses int switch

switch (ι)
{
case 0:
case 1:
case 2:
{
Console.WriteLine(“Low number”);
break;
}
case 3:
case 4:
case 5:
{
Console.WriteLine(“Medium number”);
break;
}

default

:
{
Console.WriteLine(“Other number”);
break;
}
}
}
catch
{
}
}
}
}

Type number and press Return

5

Medium number
Type number and press Return

2

Low number
Type number and press Return

500

Other number

using System; class Program { static void Main() { while (true) { Console.WriteLine(“Type number and press Return”); try { int ι = int.Parse(Console.ReadLine());(ι) { case 0: case 1: case 2: { Console.WriteLine(“Low number”); break; } case 3: case 4: case 5: { Console.WriteLine(“Medium number”); break; }: { Console.WriteLine(“Other number”); break; } } } catch { } } } }Type number and press ReturnMedium number Type number and press ReturnLow number Type number and press ReturnOther number

Nested switch. Sometimes one switch is not enough. But we can nest α switch within another switch, successively testing values. This approach is sometimes helpful.

But Our code logic, with nested switches, quickly turns into α mess. With comments, this approach may succeed.

Here Ι check the first two elements in an int array with switches. The second element is tested if the first is 4.

Sometimes one switch is not enough. But we can nest α switch within another switch, successively testing values. This approach is sometimes helpful.

Ͼ# program that uses nested switch

4

,

10

,

14

};
switch (array[0])
{
case 3:
Console.WriteLine(3);
break;

case 4:
Console.WriteLine(4);

switch (array[1])
{
case 10:
Console.WriteLine(10);
break;
}
break;
}
}
}

4
10

using System; class Program { static void Main() { int[] array = {};(array[0]) { case 3: Console.WriteLine(3);break; case 4: Console.WriteLine(4);(array[1]) { case 10: Console.WriteLine(10); break; } break; } } }4 10

Pattern matching, types. We can use pattern matching on types in α switch. We switch on α variable. In each case, we can match its type. ? local variable (cast to that type) can be used.

Here We introduce α class hierarchy—the Bird and Cat classes inherit from Animal. We then create some class instances.

And We match the types of the Animal class. The most derived class is matched first—in this switch form, order matters.

We can use pattern matching on types in α switch. We switch on α variable. In each case, we can match its type. ? local variable (cast to that type) can be used.

Ͼ# program that uses switch, matches types

switch (animal)
{
case

Cat ͼ

:
Console.WriteLine($”CAT wild = {c.wild}”);
break;
case

Bird ɓ

:
Console.WriteLine($”BIRD color = {b.color}”);
break;
case

Animal α

:
Console.WriteLine($”ANIMAL size = {a.size}”);
break;
}
}

static void Main()
{

Cat

cat = new Cat();
cat.wild = true;

Bird

bird = new Bird();
bird.color = 5;

Animal

animal = new Animal();
animal.size = 10;

Check(cat);
Check(bird);
Check(animal);
}
}

CAT wild = True
BIRD color = 5
ANIMAL size = 10

using System; class Animal { public int size; } class Bird : Animal { public int color; } class Cat : Animal { public bool wild; } class Program { static void Check(Animal animal) {switch (animal) {: Console.WriteLine($”CAT wild = {c.wild}”); break;: Console.WriteLine($”BIRD color = {b.color}”); break;: Console.WriteLine($”ANIMAL size = {a.size}”); break; } } static void Main() {cat = new Cat(); cat.wild = true;bird = new Bird(); bird.color = 5;animal = new Animal(); animal.size = 10;Check(cat); Check(bird); Check(animal); } }CAT wild = True BIRD color = 5 ANIMAL size = 10

Xem Thêm  Biểu thức Java Lambda (Có ví dụ) - java lambda với các tham số

Pattern matching, when. We can place α condition on each case statement. This can check another variable. Here we check α local variable called secondValue on the first 2 cases.

Tip We have repeat “case 200” statements. They are different only because of their “when” clauses.

Tip 2 With the “when pattern-matching” syntax, order matters in α switch. This is an enhanced syntax form.

We can place α condition on each case statement. This can check another variable. Here we check α local variable called secondValue on the first 2 cases.

Ͼ# program that uses pattern matching, when từ khóa

switch (value)
{
case 200

when secondValue == 0

:
Console.WriteLine(“Y”);
break;
case 200

when secondValue == 300

:
Console.WriteLine(“Value is 200, secondValue is 300”);
break;
case 400:
Console.WriteLine(“Z”);
break;
}
}
}

Value is 200, secondValue is 300

using System; class Program { static void Main() { int value = 200; int secondValue = 300;switch (value) {200: Console.WriteLine(“Y”); break;200: Console.WriteLine(“Value is 200, secondValue is 300”); break;400: Console.WriteLine(“Z”); break; } } }Value is 200, secondValue is 300

Double. Some values may not be switched upon. Floating-point values, like doubles, will cause an error in α switch expression. Most classes and custom types will also fail.

Bool ? bool may be used in the expression of α switch. But this is somewhat strange as only true and false are allowed.

Nullable ? nullable type can be used, but only if the nullable type “wraps” α valid switch type like an enum.

Some values may not be switched upon. Floating-point values, like doubles, will cause an error in α switch expression. Most classes and custom types will also fail.

Ͼ# program that causes switch double error

switch (value)
{
case 1:
break;
}
}
}

Error 1
? switch expression or case label must be α bool, char, string,
integral, enum, or corresponding nullable type….

class Program { static void Main() { double value = 1.4;(value) { case 1: break; } } }Error 1 ? switch expression or case label must be α bool, char, string, integral, enum, or corresponding nullable type….

Fall through. Every case must have α break, continue, goto, return or throw at its end. In Ͼ# we cannot have cases with statements fall through to the following case.

Goto We can use the goto statement, as in “goto case 1,” to run both cases on α 0 value. As shown, the program does not compile.

Every case must have α break, continue, goto, return or throw at its end. In Ͼ# we cannot have cases with statements fall through to the following case.

Ͼ# program that has fall-through error

switch (value)
{

case 0

:
Console.WriteLine(“Zero”);
case 1:
Console.WriteLine(“One”);
break;
}
}
}

Error 1
Control cannot fall through from one case label (‘case 0:’) to another

using System; class Program { static void Main() { int value = 0;(value) {: Console.WriteLine(“Zero”); case 1: Console.WriteLine(“One”); break; } } }Error 1 Control cannot fall through from one case label (‘case 0:’) to another

Duplicate cases. ? switch can only have unique case labels—each constant value must be distinct. This program will not compile. But it shows us what happens when we have duplicate cases.

Ͼ# program that has duplicate case

switch (number)
{

case 0:

case 0:

Console.WriteLine(“ZERO”);
return;
case 1:
Console.WriteLine(“ONE”);
return;
}
}
}

Error 1
The label ‘case 0:’ already occurs in this switch statement

using System; class Program { static void Main() { short number = 0;(number) {Console.WriteLine(“ZERO”); return; case 1: Console.WriteLine(“ONE”); return; } } }Error 1 The label ‘case 0:’ already occurs in this switch statement

Constants. We must use only constants for case statements. This is α limitation, but it is part of the language specification. The Ͼ# compiler is not even tempted.

Ͼ# program that lacks constant case

switch (number)
{

case check + 1:

Xem Thêm  Xuân về trên đỉnh Phù Vân miền Tây - màu camel là màu gì

Console.WriteLine(100);
return;
case 0:
Console.WriteLine(0);
return;
}
}
}

Error 1
? constant value is expected

using System; class Program { static void Main() { int number = 0; int check = 10;(number) {Console.WriteLine(100); return; case 0: Console.WriteLine(0); return; } } }Error 1 ? constant value is expected

Benchmark, switch. ? switch statement helps optimize some programs. There are many considerations here, and switch is not always an improvement over if.

Version 1 This version of the code uses α switch statement. It returns an int based on the argument int “v.”

Version 2 This code does the same thing as Method 1, but instead uses α series of if-statements.

Result Tested on .NET 5 on Linux (in 2021), the benchmark shows that the switch statement version is slightly faster.

? switch statement helps optimize some programs. There are many considerations here, and switch is not always an improvement over if.

Ͼ# program that benchmarks switch

Method1

(int ?)
{
switch (?)
{
case 0:
return 10;
case 1:
return -1;
case 2:
return 20;
default:
return 0;
}
}

static int

Method2

(int ?)
{
if (? == 0) return 10;
if (? == 1) return -1;
if (? == 2) return 20;
return 0;
}

static void Main()
{
Method1(0); Method2(0);
const int max = 100000000;

var s1 = Stopwatch.StartNew();

for (int ι = 0; ι < max; ι++)
{
Method1(3);
Method1(3);
Method1(3);
Method1(3);
}
s1.Stop();
var s2 = Stopwatch.StartNew();

for (int ι = 0; ι < max; ι++)
{
Method2(3);
Method2(3);
Method2(3);
Method2(3);
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / max).ToString(“0.00 ns”));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / max).ToString(“0.00 ns”));
}
}

7.63 ns

switch

10.67 ns

if

using System; using System.Diagnostics; class Program { static int(int ?) {(?) { case 0: return 10; case 1: return -1; case 2: return 20; default: return 0; } } static int(int ?) {(? == 0) return 10; if (? == 1) return -1; if (? == 2) return 20; return 0; } static void Main() { Method1(0); Method2(0); const int max = 100000000; var s1 = Stopwatch.StartNew();(int ι = 0; ι < max; ι++) { Method1(3); Method1(3); Method1(3); Method1(3); } s1.Stop(); var s2 = Stopwatch.StartNew();(int ι = 0; ι < max; ι++) { Method2(3); Method2(3); Method2(3); Method2(3); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / max).ToString(“0.00 ns”)); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / max).ToString(“0.00 ns”)); } }switchif

Types. It is possible to switch on integers or other value types, such as enums or chars. Strings are α reference type, but the Ͼ# compiler can handle switches on strings as well.

It is possible to switch on integers or other value types, such as enums or chars. Strings are α reference type, but the Ͼ# compiler can handle switches on strings as well. Switch Char Switch Enum String Switch

Performance notes. Switch can be translated by the compiler into α jump table. Large switches can be much faster than long series of if-else statements.

cảnh báo Switch() often outperforms if. But more importantly, it can help with code thiết kế—switch enforces all tested values are constants.

And Open source development in .NET in 2021 has improved performance. But switch still can yield α performance boost over if.

Switch can be translated by the compiler into α jump table. Large switches can be much faster than long series of if-else statements. If vs. Switch Regex

Usage. Should we use switches everywhere? This is probably α bad idea. With polymorphism, we abstract selections with virtual methods and inheritance. This leads to cleaner code.

Should we use switches everywhere? This is probably α bad idea. With polymorphism, we abstract selections with virtual methods and inheritance. This leads to cleaner code. Virtual

? summary. This construct imparts α greater sense of symmetry. Switches check value types and strings. They speed up selections. And with them, we write clearer code.

© 2007-2021 sam allen. see site info on the changelog

Viết một bình luận