C
C#18h ago
ceramo89

✅ Switch - return 🤔 ( attached )

I’m getting an explanation on switch in C# and I don’t quite get what the last return outside the scope has to do with it - does. Any idea?
No description
24 Replies
Jimmacle
Jimmacle18h ago
pretend that the value of colorNl is "rood" and follow the path the code takes return isn't part of the switch itself, but i don't know what the context is outside of this screenshot
Angius
Angius18h ago
The code shown here seems a bit out of context. Looks like it should be inside of a method Then, the return would make more sense
OptoCloud
OptoCloud18h ago
if colorNl is "groen" code flows like this:
No description
OptoCloud
OptoCloud18h ago
if it doesnt match any of the cases it flows like this:
No description
OptoCloud
OptoCloud18h ago
if that makes sense break exits the switch
Noah
Noah18h ago
couldn't you just return instead of the
break;
break;
?
c#
case "rood":
return "red";
c#
case "rood":
return "red";
OptoCloud
OptoCloud18h ago
they could but i think the point is to learn the switch case semantics
Jimmacle
Jimmacle18h ago
yeah, the code isn't great but it conveys how the syntax is used realistically you could just use a switch expression here and make it a lot more concise
Noah
Noah18h ago
switch expression, interesting Haven't seen that very often
Jimmacle
Jimmacle18h ago
it's fairly new so older learning material won't have it specifically courses based on .NET Framework
Noah
Noah18h ago
is it something you would use tho? how is it performance wise compared to a normal switch statement?
Jimmacle
Jimmacle18h ago
if there's any difference it's not enough to matter 99.99% of the time
OptoCloud
OptoCloud18h ago
all the time
Noah
Noah18h ago
really? it doen't seem THAT usefull tbh
Jimmacle
Jimmacle18h ago
and yes, any time i'm using a switch just to get a value and not do something more complex i use the expression style it's like 1/3 the loc
Noah
Noah18h ago
hmm okay
OptoCloud
OptoCloud18h ago
No description
OptoCloud
OptoCloud18h ago
No description
Noah
Noah18h ago
how does this one work? what is the value on the left?
Noah
Noah18h ago
oh so multiple inputs?!
Mierk
Mierk17h ago
Yes. You can test the values within the 'switched' object, so he’s basically checking if RequestUrl.Host matches the given string AND AbsoluthPath matches the other string. If both pass, only then the HandleCloudfare… method is being called, otherwise it will test the next case.
Noah
Noah17h ago
Okii
ceramo89
ceramo89OP6h ago
Thanks for the responses people 👍

Did you find this page helpful?