czwartek, 16 czerwca 2016

Switching on Type

One of the first things I've learned long time before my journey with C# was a conditional statement. "If-else" really makes life simple. When I faced more complex scenarios, swich kicked it, great thing for simple factories or in my case ViewTemplateSelector. A class that contains all the views and provides DataTemplate to display current view model in.

The problem was that view is selected by view models type and switch built in C# doesn't support switching on types. What to do, what to do...Lets do a type switch!

Looking on original switch statement gives pretty clear idea how it should work.

  • First of all there's an object to switch on, however I'll have it last, supplying with Execute method after everything is set.
  • Set? Right there are the cases. So what to do when Type is matched.
  • What if is not? Oh, the default case.
  • Do I need to fall through the cases? I can't see a reason to do it here.

And thats what I came up with. default case is called fallback because it felt more like fallback value used when binding in XAML than actually default action, it's kind of last stand where you usually don't want to go in scenario I described. So I made it optional. If that ViewTemplateSelector won't be able to find view for my view model than I consider it as a mistake and don't want to let it go unnoticed. So by default, when there's no match exception will be thrown. If exception is not what you want, constructor allows you to set case for fallback.
Each case is set in dictionary and simply retrieved by key when executing switch, then it returns result of invoked Func. When case is not present, fallback is attempted and if that doesn't exist, we have exception. And thats it. All the code below.

TypeSwitch.cs

TypeSwitchTest.cs

ViewSelector.cs