Search results
I think this one is better in C# 7 or above. switch (value) { case var s when new[] { 1,2 }.Contains(s): // Do something break; default: // Do the default break; } You can also check Range in C# switch case: Switch case: can I use a range instead of a one number. OR
1. Not true -- you can use a ternary operator to consolidate the less-than-zero case into a single value, and evaluate that in the switch. – Charles Duffy. Oct 12, 2009 at 13:54. This is true. It's just a restriction of the language. You can actually do this in VB.Net, as well as other things like using value ranges.
15 lut 2018 · Depending on how complicated your nested switches are this can be fun to maintain. You might want to give some thought on moving the second nested switch to a function of its own. For example. switch (order.Status) {. case OrderStatus.New: // Do something to a new order;
18 kwi 2015 · Joel, it doesn't support fall through but it DOES support stacking (e.g., an empty case 2 in this answer executes the case 5 section). – paxdiablo Commented May 11, 2009 at 14:54
Original Answer for C# 7. A bit late to the game for this question, but in recent changes introduced in C# 7 (Available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the switch statement.
4 paź 2010 · 1. In addition to substring answer, you can do it as mystring.SubString (0,3) and check in case statement if its "abc". But before the switch statement you need to ensure that your mystring is atleast 3 in length. answered Oct 4, 2010 at 8:42. Sachin Shanbhag.
29 mar 2017 · Adding to the above answer, if you do not need the value to be used inside the case statement, you can use _. This syntax can be used to remove an unused variable warning message. switch (this.value) { case int _: //Do something else without value.
Per the C# language specification, the switch statement expression must resolve to one of sbyte, byte, sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type. This means you cannot switch on Tuple or other higher-order types. You could try to pack the values together, assuming there is room.
26 mar 2014 · This won't directly solve your problem as you want to switch on your own user-defined types, but for the benefit of others who only want to switch on built-in types, you can use the TypeCode enumeration: switch (Type.GetTypeCode(node.GetType())) {. case TypeCode.Decimal: // Handle Decimal.
24 sie 2011 · Nope, switch statement requires compile time constants. The statement message.Contains("test") can evaluate true or false depending on the message so it is not a constant thus cannot be used as a 'case' for switch statement.