Reputation: 21
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)
{
}
}
}
Upvotes: 1
Views: 121
Reputation: 53
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 ?
Upvotes: 1
Reputation: 9679
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();
}
Upvotes: 0
Reputation: 157126
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.
Upvotes: 2