Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better alternative than this to 'switch on type'?

Seeing as C# can't switch on a Type (which I gather wasn't added as a special case because is relationships mean that more than one distinct case might apply), is there a better way to simulate switching on type other than this?

void Foo(object o) {     if (o is A)     {         ((A)o).Hop();     }     else if (o is B)     {         ((B)o).Skip();     }     else     {         throw new ArgumentException("Unexpected type: " + o.GetType());     } } 
like image 744
xyz Avatar asked Nov 18 '08 15:11

xyz


People also ask

What can I use instead of a switch statement in JavaScript?

Luckily, JavaScript's object literals are a pretty good alternative for most switch statement use-cases I can think of. The idea is to define an object with a key for each case you would have in a switch statement. Then you can access its value directly using the expression you would pass to the switch statement.

What can be use instead of switch case in C++?

In this case, you could also use std::array<int, 5> , which, unlike std::vector<int> , can be constexpr .

Should I avoid switch statements?

We must find an alternative to switch statements. Last but not least, because a switch statement requires us to modify a lot of classes, it violates the Open-Closed Principle from the SOLID principles. To conclude, switch statement are bad because they are error-prone and they are not maintainable.


1 Answers

With C# 7, which shipped with Visual Studio 2017 (Release 15.*), you are able to use Types in case statements (pattern matching):

switch(shape) {     case Circle c:         WriteLine($"circle with radius {c.Radius}");         break;     case Rectangle s when (s.Length == s.Height):         WriteLine($"{s.Length} x {s.Height} square");         break;     case Rectangle r:         WriteLine($"{r.Length} x {r.Height} rectangle");         break;     default:         WriteLine("<unknown shape>");         break;     case null:         throw new ArgumentNullException(nameof(shape)); } 

With C# 6, you can use a switch statement with the nameof() operator (thanks @Joey Adams):

switch(o.GetType().Name) {     case nameof(AType):         break;     case nameof(BType):         break; } 

With C# 5 and earlier, you could use a switch statement, but you'll have to use a magic string containing the type name... which is not particularly refactor friendly (thanks @nukefusion)

switch(o.GetType().Name) {   case "AType":     break; } 
like image 80
Zachary Yates Avatar answered Sep 19 '22 21:09

Zachary Yates