0

It is c# version 8.

I have a method Dispatch<T>(T payload)

I also have T1:T, T2:T, ... T8:T

is it possible to rewrite this:

if(data is T1)
   Dispatch((T1)data);
if(data is T2)
   Dispatch((T2)data);
...
if(data is T8)
   Dispatch((T8)data);

so when someone adds T9:T this part of code do not change at all?

I am aware I can use new switch statement, but it is basically the same.

user2299523
  • 111
  • 3
  • Generally the best way to manage Dispatch is to use virtual methods, either with a common base class or a common interface. You probably want an `else` before all but the first `if` statement in your code. Personally, I'd prefer a pattern-matching switch statement, but that's preference. Even if you use an `if`, consider using pattern matching, it's less susceptible to copy/paste bugs: `if (data is T1 t1data) { Dispatch (t1Data); } else if ...` – Flydog57 Jan 06 '21 at 00:40
  • 2
    Added another duplicate as it may give you standalone answer for `Dispatch ((dynamic)data)` code (also indeed if one reads past first half of accepted answer in one suggested by @Peter all is covered there just fine) – Alexei Levenkov Jan 06 '21 at 00:40
  • @Flydog57 adding processing methods to DTOs is very questionable... so I would not call it "the best"... "the most object-oriented" would be do so. – Alexei Levenkov Jan 06 '21 at 00:42
  • Do you have overloads of `Dispatch` for all of your `TN` types? If not, you can just call `Dispatch(data);` The cast does nothing useful here in that case – Flydog57 Jan 06 '21 at 00:43
  • If you want to make it "List-ish" (aka _Table Driven_), an alternative to repetitive `if then else if then else` and `switch` is to create something like a `Dictionary` then you just have a dictionary initializer that looks like a list of `{ typeof(T1), ()=>Dispatch((T1)data); }`. It doesn't buy you very much other than a tiny bit of code cleanliness – Flydog57 Jan 06 '21 at 00:49
  • `Dispatch((dynamic)data)` did exactly what I wanted. Quite new to asking on SO so did not spot duplicate. Thanks everyone. Now should I delete the question since it is closed? – user2299523 Jan 06 '21 at 01:06

0 Answers0