I fail to find documentation addressing this issue. (perhaps I am just bad at using google...) My guess is that the answer is negative, however I didn't understand where this is addressed in the documentation. To be precise my question is the following.
Suppose, I want to execute something like this:
DirectoryInfo someDir = new DirectoryInfo(@".\someDir");
Console.WriteLine($"Would you like to delete the directory {someDir.FullName}?");
string response = Console.ReadLine().ToLower();
response switch
{
"yes" => { someDir.Delete(); ... MoreActions},
_ => DoNothing()
};
I understand that I can achieve the desired behavior by using the regular switch or if/else, however I was curious whether it is possible to use switch expression in this case.
In C programming language, a block is created using a pair of curly braces. The beginning of the block is denoted by an open curly brace '{' and the end is denoted by a closing curly brace '}'. The block collects statements together into a single compound statements. The C code bellow shows two blocks.
Use the C Function block in cases where you need to allocate and deallocate memory, preprocess and postprocess external code symbols, or initialize and terminate persistent data. To call simple C code, use the C Caller block.
Block coding allows younger kids to learn the fundamentals of coding in a simpler format. It's also powerful enough to build applications and games. Block-based programming languages can also be used by adults who are beginners to coding.
however I didn't understand where this is addressed in the documentation
This is stated pretty clear here:
There are several syntax improvements here:
- The variable comes before the switch keyword. The different order makes it visually easy to distinguish the switch expression from the switch statement.
- The case and : elements are replaced with =>. It's more concise and intuitive.
- The default case is replaced with a _ discard.
- The bodies are expressions, not statements.
{ someDir.Delete(); ... MoreActions}
is not an expression.
However, you can abuse every feature, as they say :)
You can make the switch expression evaluate to an Action
, and invoke that action:
Action a = response switch
{
"yes" => () => { ... },
_ => () => { .... }
};
a();
You can even reduce this to a single statement:
(response switch
{
"yes" => (Action)(() => { ... }),
_ => () => { ... }
})();
But just don't do this...
As per documentation: The bodies are expressions, not statements.
You can do something like this though:
Action fn = response switch
{
"yes" => () => { BlockTest(); },
_ => () => { OldTest(); }
};
You can also introduce local function (C# 7.0 and above) and do something like:
response switch
{
"yes" => DoSomething(),
_ => DoNothing()
};
void DoSomething()
{
someDir.Delete();
... MoreActions
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With