1

How can I optimize the below code, the below code contains an object array that might have different type of class objects. I would prefer to move to switch case instead of if...else... how could I do it.

object[] emailObjs;
for (int i = 0; i < emailObjs.Length; i++)
{
if (emailObjs[i] != null)
    {
       if (emailObjs[i] is Rfq)
       {

       }
       else if (emailObjs[i] is RfqBid)
       {

       }
       else if (emailObjs[i] is RfqProjManager)
       {

       }
    }
}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555

3 Answers3

2

Use C# 7 pattern matching in a switch statement with a type check:

switch (emailObjs[i])
{
    case Rfq r:
        {
            // use r;
            break;
        }
    case RfqBid r:
        {
            // use r;
            break;
        }
}

Although this will compact your code significantly, performance-wise it wouldn't have much benefit over an bunch of if statements, like in your sample code.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

Here is my try:

Rfq, RfqBid, and RfqProjManager implement the same interface. Let's call it IRfq.

interface
{
     void DoSomeWork();
}

Then, your for loop could be like this:

for (int i = 0; i < emailObjs.Length; i++)
{
    if (emailObjs[i] != null && emailObjs is IRfq)
    {
           ((IRfq)emailObjs[i]).DoSomeWork();
    }
}

Is it possible with your design ?

Christophe
  • 53
  • 5
0

Define for all 3 classes common interface with one method:

public interface IRfq
{
    void DoSomething();
}

public class Rfq : IRfq
{
    public void DoSomething()
    {
        //...
    }
}

public class RfqBid : IRfq
{
    public void DoSomething()
    {
        //...
    }
}

public class RfqProjManager : IRfq
{
    public void DoSomething()
    {
        //...
    }
}

And you could do just one call in your for loop.

IRfq[] emailObjs;
for (int i = 0; i < emailObjs.Length; i++)
{
   emailObjs[i]?.DoSomething();
}
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
  • 2
    _If_ they want to call `DoSomething()` on all objects and it doesn't already have a base class defining that method. – CodeCaster Mar 27 '17 at 07:47