Personally, I only know that dynamic cannot be used in pattern matching which is considered a pity :(
dynamic foo = 10;
switch(foo) {
case int i:
break;
}
Also, valued tuple/neo-tuples cannot be used in pattern matching:
dynamic foo = (420, 360);
switch(foo) {
case (int, int) i:
break;
}
It was removed in current version of C#7 and was assigned for future usage.
What are the other things I cannot do?
The new pattern matching features in C# 7 consist of the following:
Support for type switching,
Simple use of var patterns,
The addition of when guards to case statements,
the x is T y pattern expression.
Your examples focus on the first of these. And type switching is likely to be the most popular and commonly used of these new features. Whilst there are limitations, such as those that you mention, other features can be used to work around many of them.
For example, your first limitation is easily solved by boxing foo to object:
dynamic foo = 10;
switch ((object)foo)
{
case int i:
Console.WriteLine("int");
break;
default:
Console.WriteLine("other");
break;
}
Will print int as expected.
The var pattern and a guard can be used to work around your second restriction:
dynamic foo = (420, 360);
switch (foo)
{
case var ii when ii.GetType() == typeof((int, int)):
Console.WriteLine("(int,int)");
break;
default:
Console.WriteLine("other");
break;
}
will print (int,int).
Additionally, value tuples can be used for type switching, you just have to use the long-hand syntax:
var foo = (420, 360);
switch (foo)
{
case ValueTuple<int,int> x:
Console.WriteLine($"({x.Item1},{x.Item2})");
break;
default:
Console.WriteLine("other");
break;
}
The above will print (420,360).
For me, personally, the biggest restriction to pattern matching in C# 7 is the lack of pattern matching expressions using the match keyword. Originally, the following was planned for this release, but was pulled due to time constraints:
var x = 1;
var y = x match (
case int _ : "int",
case * : "other"
);
This can be worked around using switch, but it's messy:
var x = 1;
var y = IntOrOther(x);
...
private string IntOrOther(int i)
{
switch (i)
{
case int _ : return "int";
default: return "other";
}
}
But help is at hand here with numerous 3rd party pattern matching libraries, such as my own Succinc<T> library, which let's you write it as:
var x = 1;
var y = x.TypeMatch().To<string>()
.Caseof<int>().Do("int")
.Else("other")
.Result();
It's not as good as having the match keyword, but it's an optional workaround until that feature appears in a later language release.
To really understand the restrictions imposed by C# 7, it's worth referring to the the pattern matching spec on GitHub and comparing that with what will be in the next release of C#. Looking at it though, it becomes apparent that there are work-arounds to all of these.
This question was originally closed because it's open-ended as currently phrased. To give a couple of silly examples, restrictions to C# 7's pattern matching are that it won't make you a perfect cup of coffee, or fly you across the world in seconds ... but I prefer to answer the spirit of the question. And the answer really is that the only restriction is your imagination. If you don't let that restrict you, then one must take into account the fact that the work-arounds have readability and/or performance implications. They are likely the only real-world restrictions.
Related
I have a list of different types of images I need to store in a database, they all have a type description such as Indoor or GardenSummer and things like that, but there are a lot of the descriptions that contain repeated words, like GardenSummer and AreaSummer1KM for example both contain "Summer", so is there a way for me to do something like this in c#:
open System
let strs = ["Kitchen"; "GardenSummer"; "GardenWinter"; "AreaSummer1KM"; "PoolIndoors"; "LivingRoom"; "BathRoom"]
let switch (x: string) = match x with
| a when a.Contains "Summer" -> Some "Summer" // here
| b when b.Contains "Winter" -> Some "Winter" // here
| "Exterior" | "ParkFacilities" -> Some "Outdoors"
| "Kitchen" | "Landing" -> Some "Indoors"
| c when c.Contains "Room" -> Some "Indoors" // and here
| _ -> None
let sorted = List.map switch strs
// part from here and down was just added to print the contents, and isn't a part of the issue
let printOption = function
| Some v -> v.ToString () |> Console.WriteLine
| None -> "No Match" |> Console.WriteLine
List.iter printOption sorted
is there a way for me to switch on str.Contains(str2) without making a bunch of else ifs?
The short answer is no.
The slightly longer answer is "no, for a good reason". The switch statement is actually quite a smart statement, that performs better than a chain of if-else if statements in many cases (a good example being the typical switch (MessageType) ...). To do this, however, it requires certain contracts to be held. In the end, it doesn't evaluate every possibility. It performs something similar to a binary search on the possible options.
In the end, your F# code probably does the equivalent of if-else if statements, rather than the equivalent of switch in C#.
Of course, nothing prevents you from creating your own method that would be syntactically similar to F#'s match. Anonymous delegates, generic functions, all those make it rather easy to write such syntax shorteners :)
And of course, there's other options too, like using regular expressions or such. Calling Contains 10 times in a row is going to mean a significant performance penalty if the searched string is long.
Some sample regexes for your data and switches. The common code is as follows:
void Main()
{
var data =
new []
{
"Kitchen", "GardenSummer", "GardenWinter", "AreaSummer1KM",
"PoolIndoors", "LivingRoom", "BathRoom", "Exterior", "ParkFacilities"
};
foreach (var str in data)
{
Matcher(str).Dump();
}
}
Now the thing we're going to change is the Matcher method implementation.
First, to just simplify the whole thing and avoid multiple string matching (comparing strings isn't exactly free):
Regex matcherRegex = new Regex("(Summer)|(Winter)|(^Exterior|ParkFacilities$)",
RegexOptions.Compiled);
string Matcher(string input)
{
var m = matcherRegex.Match(input);
if (m.Groups.Count == 4)
{
if (m.Groups[0].Success) return "Summer";
else if (m.Groups[1].Success) return "Winter";
else if (m.Groups[2].Success) return "Outdoors";
}
return null;
}
So, we still have a if-else chain, but we no longer traverse the strings multiple times. It also allows you to easily specify the conditions you want.
One way to improve this to be more "switchy" is by using LINQ. This is definitely not something you want to do for performance reasons, it's only about aesthetics:
var groupIndex = m.Groups.OfType<Group>()
.Skip(1)
.Select((i, idx) => new { Item = i, Index = idx + 1 })
.Where(i => i.Item.Success)
.Select(i => i.Index)
.FirstOrDefault();
switch (groupIndex)
{
case 0: return null;
case 1: return "Summer";
case 2: return "Winter";
case 3: return "Outdoors";
}
Basically, I get the index of the matched group, and use a switch on that. As I said before, this is probably going to be slower than the first variant, at least due to the LINQ overhead.
You can also use named captures to get the matched groups by name, rather than by index, which is a bit more maintainable. Also, for simple cases, you could use the named group name to avoid the switch altogether:
Regex matcherRegex =
new Regex("(?<Summer>Summer)"
+ "|(?<Winter>Winter)"
+ "|(?<Outdoors>(^Exterior|ParkFacilities$))",
RegexOptions.Compiled | RegexOptions.ExplicitCapture);
string Matcher(string input)
{
return matcherRegex.Match(input)
.Groups
.OfType<Group>()
.Select((i, idx) => new { Item = i, Index = idx })
.Skip(1)
.Where(i => i.Item.Success)
.Select(i => matcherRegex.GroupNameFromNumber(i.Index))
.FirstOrDefault();
}
All of those are just samples, you may want to change those for better edge case or exception handling, and performance, but it shows the ideas.
The last version in particular is handy in that there's nothing preventing you from using this as a common method that handles all the string "switches" that you can explain in regular expressions. Sadly, group names allow a lot of unicode characters, but not whitespaces; it's nothing you couldn't work around, though.
You could even build the pattern matcher automatically, for example by passing Expression<Func<...>> to a helper method, but that's going into complicated territory :)
I'm trying to understand how well C# and F# can play together. I've taken some code from the F# for Fun & Profit blog which performs basic validation returning a discriminated union type:
type Result<'TSuccess,'TFailure> =
| Success of 'TSuccess
| Failure of 'TFailure
type Request = {name:string; email:string}
let TestValidate input =
if input.name = "" then Failure "Name must not be blank"
else Success input
When trying to consume this in C#; the only way I can find to access the values against Success and Failure (failure is a string, success is the request again) is with big nasty casts (which is a lot of typing, and requires typing actual types that I would expect to be inferred or available in the metadata):
var req = new DannyTest.Request("Danny", "fsfs");
var res = FSharpLib.DannyTest.TestValidate(req);
if (res.IsSuccess)
{
Console.WriteLine("Success");
var result = ((DannyTest.Result<DannyTest.Request, string>.Success)res).Item;
// Result is the Request (as returned for Success)
Console.WriteLine(result.email);
Console.WriteLine(result.name);
}
if (res.IsFailure)
{
Console.WriteLine("Failure");
var result = ((DannyTest.Result<DannyTest.Request, string>.Failure)res).Item;
// Result is a string (as returned for Failure)
Console.WriteLine(result);
}
Is there a better way of doing this? Even if I have to manually cast (with the possibility of a runtime error), I would hope to at least shorten access to the types (DannyTest.Result<DannyTest.Request, string>.Failure). Is there a better way?
Working with discriminated unions is never going to be as straightforward in a language that does not support pattern matching. However, your Result<'TSuccess, 'TFailure> type is simple enough that there should be some nice way to use it from C# (if the type was something more complicated, like an expression tree, then I would probably suggest to use the Visitor pattern).
Others already mentioned a few options - both how to access the values directly and how to define Match method (as described in Mauricio's blog post). My favourite method for simple DUs is to define TryGetXyz methods that follow the same style of Int32.TryParse - this also guarantees that C# developers will be familiar with the pattern. The F# definition looks like this:
open System.Runtime.InteropServices
type Result<'TSuccess,'TFailure> =
| Success of 'TSuccess
| Failure of 'TFailure
type Result<'TSuccess, 'TFailure> with
member x.TryGetSuccess([<Out>] success:byref<'TSuccess>) =
match x with
| Success value -> success <- value; true
| _ -> false
member x.TryGetFailure([<Out>] failure:byref<'TFailure>) =
match x with
| Failure value -> failure <- value; true
| _ -> false
This simply adds extensions TryGetSuccess and TryGetFailure that return true when the value matches the case and return (all) parameters of the discriminated union case via out parameters. The C# use is quite straightforward for anyone who has ever used TryParse:
int succ;
string fail;
if (res.TryGetSuccess(out succ)) {
Console.WriteLine("Success: {0}", succ);
}
else if (res.TryGetFailure(out fail)) {
Console.WriteLine("Failuere: {0}", fail);
}
I think the familiarity of this pattern is the most important benefit. When you use F# and expose its type to C# developers, you should expose them in the most direct way (the C# users should not think that the types defined in F# are non-standard in any way).
Also, this gives you reasonable guarantees (when it is used correctly) that you will only access values that are actually available when the DU matches a specific case.
A really nice way to do this with C# 7.0 is using switch pattern matching, it's allllmost like F# match:
var result = someFSharpClass.SomeFSharpResultReturningMethod()
switch (result)
{
case var checkResult when checkResult.IsOk:
HandleOk(checkResult.ResultValue);
break;
case var checkResult when checkResult.IsError:
HandleError(checkResult.ErrorValue);
break;
}
EDIT: C# 8.0 is around the corner and it is bringing switch expressions, so although I haven't tried it yet I am expecting we will be able to do something like this this:
var returnValue = result switch
{
var checkResult when checkResult.IsOk: => HandleOk(checkResult.ResultValue),
var checkResult when checkResult.IsError => HandleError(checkResult.ErrorValue),
_ => throw new UnknownResultException()
};
See https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/ for more info.
How about this? It's inspired by #Mauricio Scheffer's comment above and the CSharpCompat code in FSharpx.
C#:
MyUnion u = CallIntoFSharpCode();
string s = u.Match(
ifFoo: () => "Foo!",
ifBar: (b) => $"Bar {b}!");
F#:
type MyUnion =
| Foo
| Bar of int
with
member x.Match (ifFoo: System.Func<_>, ifBar: System.Func<_,_>) =
match x with
| Foo -> ifFoo.Invoke()
| Bar b -> ifBar.Invoke(b)
What I like best about this is that it removes the possibility of a runtime error. You no longer have a bogus default case to code, and when the F# type changes (e.g. adding a case) the C# code will fail to compile.
You can use C# type aliasing to simplify referencing the DU Types in a C# File.
using DanyTestResult = DannyTest.Result<DannyTest.Request, string>;
Since C# 8.0 and later have Structural pattern matching, it's easy to do the following:
switch (res) {
case DanyTestResult.Success {Item: var req}:
Console.WriteLine(req.email);
Console.WriteLine(req.name);
break;
case DanyTestResult.Failure {Item: var msg}:
Console.WriteLine("Failure");
Console.WriteLine(msg);
break;
}
This strategy is the simplest as it works with reference type F# DU without modification.
The syntax C# syntax could be reduced more if F# added a Deconstruct method to the codegen for interop. DanyTestResult.Success(var req)
If your F# DU is a struct style, you just need to pattern match on the Tag property without the type. {Tag:DanyTestResult.Tag.Success, SuccessValue:var req}
Probably, one of the simplest ways to accomplish this is by creating a set of extension methods:
public static Result<Request, string>.Success AsSuccess(this Result<Request, string> res) {
return (Result<Request, string>.Success)res;
}
// And then use it
var successData = res.AsSuccess().Item;
This article contains a good insight. Quote:
The advantage of this approach is 2 fold:
Removes the need to explicitly name types in code and hence gets back the advantages of type inference;
I can now use . on any of the values and let Intellisense help me find the appropriate method to use;
The only downfall here is that changed interface would require refactoring the extension methods.
If there are too many such classes in your project(s), consider using tools like ReSharper as it looks not very difficult to set up a code generation for this.
I had this same issue with the Result type. I created a new type of ResultInterop<'TSuccess, 'TFailure> and a helper method to hydrate the type
type ResultInterop<'TSuccess, 'TFailure> = {
IsSuccess : bool
Success : 'TSuccess
Failure : 'TFailure
}
let toResultInterop result =
match result with
| Success s -> { IsSuccess=true; Success=s; Failure=Unchecked.defaultof<_> }
| Failure f -> { IsSuccess=false; Success=Unchecked.defaultof<_>; Failure=f }
Now I have the choice of piping through toResultInterop at the F# boundary or doing so within the C# code.
At the F# boundary
module MyFSharpModule =
let validate request =
if request.isValid then
Success "Woot"
else
Failure "request not valid"
let handleUpdateRequest request =
request
|> validate
|> toResultInterop
public string Get(Request request)
{
var result = MyFSharpModule.handleUpdateRequest(request);
if (result.IsSuccess)
return result.Success;
else
throw new Exception(result.Failure);
}
After the interop in Csharp
module MyFSharpModule =
let validate request =
if request.isValid then
Success "Woot"
else
Failure "request not valid"
let handleUpdateRequest request = request |> validate
public string Get(Request request)
{
var response = MyFSharpModule.handleUpdateRequest(request);
var result = Interop.toResultInterop(response);
if (result.IsSuccess)
return result.Success;
else
throw new Exception(result.Failure);
}
I'm using the next methods to interop unions from F# library to C# host. This may add some execution time due to reflection usage and need to be checked, probably by unit tests, for handling right generic types for each union case.
On F# side
type Command =
| First of FirstCommand
| Second of SecondCommand * int
module Extentions =
let private getFromUnionObj value =
match value.GetType() with
| x when FSharpType.IsUnion x ->
let (_, objects) = FSharpValue.GetUnionFields(value, x)
objects
| _ -> failwithf "Can't parse union"
let getFromUnion<'r> value =
let x = value |> getFromUnionObj
(x.[0] :?> 'r)
let getFromUnion2<'r1,'r2> value =
let x = value |> getFromUnionObj
(x.[0] :?> 'r1, x.[1] :? 'r2)
On C# side
public static void Handle(Command command)
{
switch (command)
{
case var c when c.IsFirstCommand:
var data = Extentions.getFromUnion<FirstCommand>(change);
// Handler for case
break;
case var c when c.IsSecondCommand:
var data2 = Extentions.getFromUnion2<SecondCommand, int>(change);
// Handler for case
break;
}
}
I know switch statements are not available in CodeDom and how compilers deal with switch statement.
So for performance reasons when many cases are present, I don't want to use If-else
Why the switch statement and not if-else?
Is is possible to generate code to simulate a Jump table for a given case list.
switch(value) {
case 0: return Method0();
case 1: return Method1();
case 4; return Method4();
}
Would produce:
private delegate object Method();
Method[] _jumpTable = new Method[] { Method0, Method1, null, null, Method4 };
private object GetValue(int value)
{
if (value < 0 || value > 4)
return null;
return _jumpTable[value]();
}
What is the best way to analyze the case list and generate an array if there are holes in the sequence or the list is sparse?
You might want to take a look at The Roslyn Project for the code anaylsis. If the table is large and especially sparse then if/else might be better (given modern CPU caches). Roslyn should let you walk the DOM and acquire the case values which can then be sorted (perhaps in a single linq stmt). I believe that you mean to have 'break;'s in your switch above. If you implement something like this I would test it very carefully to ensure that it actually does improve performance.
If I have a switch-case statement where the object in the switch is string, is it possible to do an ignoreCase compare?
I have for instance:
string s = "house";
switch (s)
{
case "houSe": s = "window";
}
Will s get the value "window"? How do I override the switch-case statement so it will compare the strings using ignoreCase?
A simpler approach is just lowercasing your string before it goes into the switch statement, and have the cases lower.
Actually, upper is a bit better from a pure extreme nanosecond performance standpoint, but less natural to look at.
E.g.:
string s = "house";
switch (s.ToLower()) {
case "house":
s = "window";
break;
}
Sorry for this new post to an old question, but there is a new option for solving this problem using C# 7 (VS 2017).
C# 7 now offers "pattern matching", and it can be used to address this issue thusly:
string houseName = "house"; // value to be tested, ignoring case
string windowName; // switch block will set value here
switch (true)
{
case bool b when houseName.Equals("MyHouse", StringComparison.InvariantCultureIgnoreCase):
windowName = "MyWindow";
break;
case bool b when houseName.Equals("YourHouse", StringComparison.InvariantCultureIgnoreCase):
windowName = "YourWindow";
break;
case bool b when houseName.Equals("House", StringComparison.InvariantCultureIgnoreCase):
windowName = "Window";
break;
default:
windowName = null;
break;
}
This solution also deals with the issue mentioned in the answer by #Jeffrey L Whitledge that case-insensitive comparison of strings is not the same as comparing two lower-cased strings.
By the way, there was an interesting article in February 2017 in Visual Studio Magazine describing pattern matching and how it can be used in case blocks. Please have a look: Pattern Matching in C# 7.0 Case Blocks
EDIT
In light of #LewisM's answer, it's important to point out that the switch statement has some new, interesting behavior. That is that if your case statement contains a variable declaration, then the value specified in the switch part is copied into the variable declared in the case. In the following example, the value true is copied into the local variable b. Further to that, the variable b is unused, and exists only so that the when clause to the case statement can exist:
switch(true)
{
case bool b when houseName.Equals("X", StringComparison.InvariantCultureIgnoreCase):
windowName = "X-Window";):
break;
}
As #LewisM points out, this can be used to benefit - that benefit being that the thing being compared is actually in the switch statement, as it is with the classical use of the switch statement. Also, the temporary values declared in the case statement can prevent unwanted or inadvertent changes to the original value:
switch(houseName)
{
case string hn when hn.Equals("X", StringComparison.InvariantCultureIgnoreCase):
windowName = "X-Window";
break;
}
As you seem to be aware, lowercasing two strings and comparing them is not the same as doing an ignore-case comparison. There are lots of reasons for this. For example, the Unicode standard allows text with diacritics to be encoded multiple ways. Some characters includes both the base character and the diacritic in a single code point. These characters may also be represented as the base character followed by a combining diacritic character. These two representations are equal for all purposes, and the culture-aware string comparisons in the .NET Framework will correctly identify them as equal, with either the CurrentCulture or the InvariantCulture (with or without IgnoreCase). An ordinal comparison, on the other hand, will incorrectly regard them as unequal.
Unfortunately, switch doesn't do anything but an ordinal comparison. An ordinal comparison is fine for certain kinds of applications, like parsing an ASCII file with rigidly defined codes, but ordinal string comparison is wrong for most other uses.
What I have done in the past to get the correct behavior is just mock up my own switch statement. There are lots of ways to do this. One way would be to create a List<T> of pairs of case strings and delegates. The list can be searched using the proper string comparison. When the match is found then the associated delegate may be invoked.
Another option is to do the obvious chain of if statements. This usually turns out to be not as bad as it sounds, since the structure is very regular.
The great thing about this is that there isn't really any performance penalty in mocking up your own switch functionality when comparing against strings. The system isn't going to make a O(1) jump table the way it can with integers, so it's going to be comparing each string one at a time anyway.
If there are many cases to be compared, and performance is an issue, then the List<T> option described above could be replaced with a sorted dictionary or hash table. Then the performance may potentially match or exceed the switch statement option.
Here is an example of the list of delegates:
delegate void CustomSwitchDestination();
List<KeyValuePair<string, CustomSwitchDestination>> customSwitchList;
CustomSwitchDestination defaultSwitchDestination = new CustomSwitchDestination(NoMatchFound);
void CustomSwitch(string value)
{
foreach (var switchOption in customSwitchList)
if (switchOption.Key.Equals(value, StringComparison.InvariantCultureIgnoreCase))
{
switchOption.Value.Invoke();
return;
}
defaultSwitchDestination.Invoke();
}
Of course, you will probably want to add some standard parameters and possibly a return type to the CustomSwitchDestination delegate. And you'll want to make better names!
If the behavior of each of your cases is not amenable to delegate invocation in this manner, such as if differnt parameters are necessary, then you’re stuck with chained if statments. I’ve also done this a few times.
if (s.Equals("house", StringComparison.InvariantCultureIgnoreCase))
{
s = "window";
}
else if (s.Equals("business", StringComparison.InvariantCultureIgnoreCase))
{
s = "really big window";
}
else if (s.Equals("school", StringComparison.InvariantCultureIgnoreCase))
{
s = "broken window";
}
An extension to the answer by #STLDeveloperA. A new way to do statement evaluation without multiple if statements as of C# 7 is using the pattern matching switch statement, similar to the way #STLDeveloper though this way is switching on the variable being switched
string houseName = "house"; // value to be tested
string s;
switch (houseName)
{
case var name when string.Equals(name, "Bungalow", StringComparison.InvariantCultureIgnoreCase):
s = "Single glazed";
break;
case var name when string.Equals(name, "Church", StringComparison.InvariantCultureIgnoreCase):
s = "Stained glass";
break;
...
default:
s = "No windows (cold or dark)";
break;
}
The visual studio magazine has a nice article on pattern matching case blocks that might be worth a look.
In some cases it might be a good idea to use an enum. So first parse the enum (with ignoreCase flag true) and than have a switch on the enum.
SampleEnum Result;
bool Success = SampleEnum.TryParse(inputText, true, out Result);
if(!Success){
//value was not in the enum values
}else{
switch (Result) {
case SampleEnum.Value1:
break;
case SampleEnum.Value2:
break;
default:
//do default behaviour
break;
}
}
One possible way would be to use an ignore case dictionary with an action delegate.
string s = null;
var dic = new Dictionary<string, Action>(StringComparer.CurrentCultureIgnoreCase)
{
{"house", () => s = "window"},
{"house2", () => s = "window2"}
};
dic["HouSe"]();
// Note that the call doesn't return text, but only populates local variable s.
// If you want to return the actual text, replace Action to Func<string> and values in dictionary to something like () => "window2"
Here's a solution that wraps #Magnus 's solution in a class:
public class SwitchCaseIndependent : IEnumerable<KeyValuePair<string, Action>>
{
private readonly Dictionary<string, Action> _cases = new Dictionary<string, Action>(StringComparer.OrdinalIgnoreCase);
public void Add(string theCase, Action theResult)
{
_cases.Add(theCase, theResult);
}
public Action this[string whichCase]
{
get
{
if (!_cases.ContainsKey(whichCase))
{
throw new ArgumentException($"Error in SwitchCaseIndependent, \"{whichCase}\" is not a valid option");
}
//otherwise
return _cases[whichCase];
}
}
public IEnumerator<KeyValuePair<string, Action>> GetEnumerator()
{
return _cases.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _cases.GetEnumerator();
}
}
Here's an example of using it in a simple Windows Form's app:
var mySwitch = new SwitchCaseIndependent
{
{"hello", () => MessageBox.Show("hello")},
{"Goodbye", () => MessageBox.Show("Goodbye")},
{"SoLong", () => MessageBox.Show("SoLong")},
};
mySwitch["HELLO"]();
If you use lambdas (like the example), you get closures which will capture your local variables (pretty close to the feeling you get from a switch statement).
Since it uses a Dictionary under the covers, it gets O(1) behavior and doesn't rely on walking through the list of strings. Of course, you need to construct that dictionary, and that probably costs more. If you want to reuse the Switch behavior over and over, you can create and initialize the the SwitchCaseIndependent object once and then use it as many times as you want.
It would probably make sense to add a simple bool ContainsCase(string aCase) method that simply calls the dictionary's ContainsKey method.
I would say that with switch expressions (added in C# 8.0), discard patterns and local functions the approaches suggested by #STLDev and #LewisM can be rewritten in even more clean/shorter way:
string houseName = "house"; // value to be tested
// local method to compare, I prefer to put them at the bottom of the invoking method:
bool Compare(string right) => string.Equals(houseName, right, StringComparison.InvariantCultureIgnoreCase);
var s = houseName switch
{
_ when Compare("Bungalow") => "Single glazed",
_ when Compare("Church") => "Stained glass",
// ...
_ => "No windows (cold or dark)" // default value
};
It should be sufficient to do this:
string s = "houSe";
switch (s.ToLowerInvariant())
{
case "house": s = "window";
break;
}
The switch comparison is thereby culture invariant. As far as I can see this should achieve the same result as the C#7 Pattern-Matching solutions, but more succinctly.
I hope this helps try to convert the whole string into particular case either lower case or Upper case and use the Lowercase string for comparison:
public string ConvertMeasurements(string unitType, string value)
{
switch (unitType.ToLower())
{
case "mmol/l": return (Double.Parse(value) * 0.0555).ToString();
case "mg/dl": return (double.Parse(value) * 18.0182).ToString();
}
}
Using the Case Insensitive Comparison:
Comparing strings while ignoring case.
switch (caseSwitch)
{
case string s when s.Equals("someValue", StringComparison.InvariantCultureIgnoreCase):
// ...
break;
}
for more detail Visit this link: Switch Case When In C# Statement And Expression
Now you can use the switch expression (rewrote the previous example):
return houseName switch
{
_ when houseName.Equals("MyHouse", StringComparison.InvariantCultureIgnoreCase) => "MyWindow",
_ when houseName.Equals("YourHouse", StringComparison.InvariantCultureIgnoreCase) => "YourWindow",
_ when houseName.Equals("House", StringComparison.InvariantCultureIgnoreCase) => "Window",
_ => null
};
How to write following statement in c using switch statement in c
int i = 10;
int j = 20;
if (i == 10 && j == 20)
{
Mymethod();
}
else if (i == 100 && j == 200)
{
Yourmethod();
}
else if (i == 1000 || j == 2000) // OR
{
Anymethod();
}
EDIT:
I have changed the last case from 'and' to 'or' later. So I appologise from people who answered my question before this edit.
This scenario is for example, I just wanted to know that is it possible or not. I have google this and found it is not possible but I trust gurus on stackoverflow more.
Thanks
You're pressing for answers that will unnaturally force this code into a switch - that's not the right approach in C, C++ or C# for the problem you've described. Live with the if statements, as using a switch in this instance leads to less readable code and the possibility that a slip-up will introduce a bug.
There are languages that will evaluate a switch statement syntax similar to a sequence of if statements, but C, C++, and C# aren't among them.
After Jon Skeet's comment that it can be "interesting to try to make it work", I'm going to go against my initial judgment and play along because it's certainly true that one can learn by trying alternatives to see where they work and where they don't work. Hopefully I won't end up muddling things more than I should...
The targets for a switch statement in the languages under consideration need to be constants - they aren't expressions that are evaluated at runtime. However, you can potentially get a behavior similar to what you're looking for if you can map the conditions that you want to have as switch targets to a hash function that will produce a perfect hash the matches up to the conditions. If that can be done, you can call the hash function and switch on the value it produces.
The C# compiler does something similar to this automatically for you when you want to switch on a string value. In C, I've manually done something similar when I want to switch on a string. I place the target strings in a table along with enumerations that are used to identify the strings, and I switch on the enum:
char* cmdString = "copystuff"; // a string with a command identifier,
// maybe obtained from console input
StrLookupValueStruct CmdStringTable[] = {
{ "liststuff", CMD_LIST },
{ "docalcs", CMD_CALC },
{ "copystuff", CMD_COPY },
{ "delete", CMD_DELETE },
{ NULL, CMD_UNKNOWN },
};
int cmdId = strLookupValue( cmdString, CmdStringTable); // transform the string
// into an enum
switch (cmdId) {
case CMD_LIST:
doList();
break;
case CMD_CALC:
doCalc();
break;
case CMD_COPY:
doCopy();
break;
// etc...
}
Instead of having to use a sequence of if statements:
if (strcmp( cmdString, "liststuff") == 0) {
doList();
}
else if (strcmp( cmdString, "docalcs") == 0) {
doCalc();
}
else if (strcmp( cmdString, "copystuff") == 0) {
doCopy();
}
// etc....
As an aside, for the string to function mapping here I personally find the table lookup/switch statement combination to be a bit more readable, but I imagine there are people who might prefer the more direct approach of the if sequence.
The set of expressions you have in your question don't look particularly simple to transform into a hash - your hash function would almost certainly end up being a sequence of if statements - you would have basically just moved the construct somewhere else. Jon Skeet's original answer was essentially to turn your expressions into a hash, but when the or operation got thrown into the mix of one of the tests, the hash function broke down.
In general you can't. What you are doing already is fine, although you might want to add an else clause at the end to catch unexpected inputs.
In your specific example it seems that j is often twice the value of i. If that is a general rule you could try to take advantage of that by doing something like this instead:
if (i * 2 == j) /* Watch out for overflow here if i could be large! */
{
switch (i)
{
case 10:
// ...
break;
case 100:
// ...
break;
// ...
}
}
(Removed original answer: I'd missed the fact that the condition was an "OR" rather than an "AND". EDIT: Ah, because apparently it wasn't to start with.)
You could still theoretically use something like my original code (combining two 32-bit integers into one 64-bit integer and switching on that), although there would be 2^33 case statements covering the last condition. I doubt that any compiler would actually make it through such code :)
But basically, no: use the if/else structure instead.