Below I've put together pseudo code of what I'm trying to do. I'm not entirely sure how to write this in C#. Is something like this possible, if so how can i do it. What i want to do is a run a function if the value returned is found.
pseudo code
string list = @"
This is a multiline statement
used for testing
"
foreach (var line in list)
{
switch (line)
{
case (line.Contains("multiline")):
Console.WriteLine("has A");
break;
case (line.Contains("testing")):
Console.WriteLine("has B");
break;
}
}
It is not possible. Using switch statement you just check the value of a given object. Try using a if:
foreach (var line in list)
{
if (line.Contains("multiline"))
Console.WriteLine("has A");
else if (line.Contains("testing"))
Console.WriteLine("has B");
}
From the MSDN docs:
The switch statement is a control statement that selects a switch section to execute from a list of candidates.
The case statement is a compile time constant.
The right use of a switch statement could be like this:
int caseSwitch = /* get a int value*/;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}
What you are trying to do is called "pattern matching". C# doesn't yet support this, though it is being actively discussed as an addition to the next release, C# 7.
There are third party solutions that allow you to achieve what you are trying to do. My own Succinc<T> library for example, would allow you to write the code as:
string list = @"
This is a multiline statement
used for testing
";
foreach (var line in list)
{
line.Match()
.Where(l => l.contains("multiline").Do(l => Console.WriteLine("has A"))
.Where(l => l.contains("testing").Do(l => Console.WriteLine("has B"))
.IgnoreElse()
.Exec();
}
It arguably leads to easier-to-follow, more functional, code than using a series of if's, though the trade-off is then in performance.
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