Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 611
accordo777 Avatar asked Dec 03 '22 18:12

accordo777


2 Answers

As Sweeper mentions in the comments, from C# 7.0 you can use the The is type pattern expression

if (msg is Tomato tomato) Handle_Tomato(tomato);

You could also use pattern matching with a switch statement (Type pattern) since C# 7.0

The type pattern enables concise type evaluation and conversion. When used with the switch statement to perform pattern matching, it tests whether an expression can be converted to a specified type and, if it can be, casts it to a variable of that type.

switch(msg)
{
   case Tomato tomato : Handle_Tomato(tomato); break;
   case Apple apple : Handle_Apple(apple); break;
   ...
}
like image 82
TheGeneral Avatar answered Dec 22 '22 23:12

TheGeneral


I'd strongly suggest not to do such checks. What if in the future there are dozens of different types? Your if statement will increase and be unmaintainable. What if the type changes? You'd have to change all the if statements as well.

You could solve this by using an interface. You already have the classes.

interface IHandler
{
    void Execute();
} 
class Orange : IHandler 
{
    public void Execute()
    {
        // do your orange stuff 
    }
}
class Tomato : IHandler
{
    public void Execute()
    {
        // do your tomato stuff
    }
}

It can be called like this.

if (msg is IHandler) ((IHandler)msg).Execute();
like image 34
imsmn Avatar answered Dec 23 '22 01:12

imsmn