jeudi 27 juin 2019

Better If statement with type checking C#

I'm currently working on a .NET 4.7.1 application. I have an If-statement to check the data type and call an handler method accordingly.

My current If statement looks like this:

// object msg = MyHelper.Deserialize(xmlString);

if (msg is Tomato) Handle_Tomato((Tomato)msg);
if (msg is Apple) Handle_Apple((Apple)msg);
if (msg is Banana) Handle_Banana((Banana)msg);
if (msg is Orange) Handle_Orange((Orange)msg);

msg is basically an object deserialized from a string.

I was wondering, if there is a better way to write my if statements?

Thank you very much!

Aucun commentaire:

Enregistrer un commentaire