0

I have a third party API that passes a parameter that is a base type. I handle each derived type separately as they have specialized functionality for each that I need to make use of.

if(parameter is DerivedTypeX) HandleParamerter(parameter as DerivedTypeX);
else if (parameter is DerivedTypeY) HandleParameter(parameter as DerivedTypeY);
...

For some reason, I can't let it go that there must be a more elegant way to handle this parameter than a massive else if block.

Flea
  • 1,490
  • 2
  • 19
  • 43
  • 1
    C# supports [pattern matching in `switch/case` statements](https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching#using-pattern-matching-switch-statements), so you could write your `if` chain as `switch` statement if that helps. – René Vogt Jul 05 '19 at 14:21
  • 1
    Why don't you declare Handle() as an abstract method in your base class, and implement the desired functionality in the derived classes? – CodeCaster Jul 05 '19 at 14:26
  • @CodeCaster I don't control the third-party API that is passing "parameter". – Flea Jul 05 '19 at 14:28
  • Well then map it to your own type, or wrap it, or make it a partial class, or... – CodeCaster Jul 05 '19 at 14:29
  • @RenéVogt A switch statement is, semantically, no different than a massive if/else block. My preference would be to use something like: HandleParameter(parameter) that uses the correct overload based on the derived type of parameter. – Flea Jul 05 '19 at 14:30
  • @CodeCaster Essentially the if/else block _is_ mapping it to my own type. I can't make it a partial class as I don't control the architecture of the third party API passing me the abstract type, "parameter". – Flea Jul 05 '19 at 14:32
  • @Fildor Yes... except that, because "parameter" is always the base, abstract type, Handle( A obj ) is always the overload called. – Flea Jul 05 '19 at 14:35
  • Yep, I got it. Missed the problem by an inch. – Fildor Jul 05 '19 at 14:35
  • @Fildor Yeah. It's more like the following: A a = new AB(); A ab = new AB(); A ac = new AC(); which is why Handle(A obj) is always called. You're thinking is along the same lines as mine though which is why I can't seem to let it go. – Flea Jul 05 '19 at 14:36
  • Yes, realized my mistake right on hitting to send the comment :-/ – Fildor Jul 05 '19 at 14:37
  • 1
    @CodeCaster The first link is exactly what I was looking for! Thank you! I'd never have found it with that different wording though. – Flea Jul 05 '19 at 14:46
  • Example with dynamic: https://dotnetfiddle.net/8NWrLE ... that's awesome. I never even considered `dynamic` before, really. – Fildor Jul 05 '19 at 14:50
  • @Fildor Me neither. Great solution! – Flea Jul 05 '19 at 14:51

0 Answers0