this post was submitted on 04 Jul 2023
9 points (84.6% liked)

.NET

1416 readers
12 users here now

Getting started

Useful resources

IDEs and code editors

Tools

Rules

Related communities

Wikipedia pages

founded 1 year ago
MODERATORS
 

What does "control falls through a switch statement" mean in this context? Control just moves on to the next statement?

I thought if there is no match and a default case doesn't exist it will raise an exception. Is it not true?

top 8 comments
sorted by: hot top controversial new old
[–] [email protected] 4 points 1 year ago (1 children)

Means it will be skipped entirely

[–] [email protected] 3 points 1 year ago (1 children)

I see, thank you! I got confused with "control falls through a switch statement" and "C++ style fall through in switch statements".

[–] [email protected] 1 points 1 year ago (1 children)

C# will let you forget simple things and crash or compile error further down the line.

[–] [email protected] 2 points 1 year ago

Unlike c++? Hehe

[–] [email protected] 2 points 1 year ago (1 children)

A switch statement will let control fall through. A switch expression will no, and will throw an exception (and there will also be a compiler warning that it's not exhaustive before you even run the code)

[–] [email protected] 3 points 1 year ago* (last edited 1 year ago) (1 children)

A switch statement will let control fall through.

I think even switch statement doesn't allow it because every case needs to be terminated with either break, return or raise. One needs to use case goto if one wants fall thought like behavior:

switch (x)
{
case "One":
    Console.WriteLine("One");
    goto case "Two";
case "Two":
    Console.WriteLine("One or two");
    break;
}

C# outlaws this, because the vast majority of case sections do not fall through, and when they do in languages that allow it, it’s often a mistake caused by the developer forgetting to write a break statement (or some other statement to break out of the switch). Accidental fall-through is likely to produce unwanted behavior, so C# requires more than the mere omission of a break: if you want fall-through, you must ask for it explicitly.

Programming C# 10 ~ Ian Griffiths

[–] [email protected] 3 points 1 year ago (1 children)

I think even switch statement doesn't allow it [...]

A switch statement allows fall through when the case itself doesn't have an implementation.

For example this is also considered a fall through:

        switch (x)
        {
            case "One":
            case "Two":
                Console.WriteLine("One or two");
                break;
        }
[–] [email protected] 1 points 1 year ago

TIL!!!

Thank you!

load more comments
view more: next ›