I have following C# code. It works fine; but the GetDestination()
method is cluttered with multiple if
conditions by using is operator.
In .Net 4.0 (or greater) what is the best way to avoid these “if” conditions?
EDIT: Role is part of the business model, and the destination is purely an artifact of one particular application using that business model.
CODE
public class Role { }
public class Manager : Role { }
public class Accountant : Role { }
public class Attender : Role { }
public class Cleaner : Role { }
public class Security : Role { }
class Program
{
static string GetDestination(Role x)
{
string destination = @"\Home";
if (x is Manager)
{
destination = @"\ManagerHomeA";
}
if (x is Accountant)
{
destination = @"\AccountantHomeC";
}
if (x is Cleaner)
{
destination = @"\Cleaner";
}
return destination;
}
static void Main(string[] args)
{
string destination = GetDestination(new Accountant());
Console.WriteLine(destination);
Console.ReadLine();
}
}
REFERENCES
string.Format(@"\{0}Home", x.GetType().Name)
. If that's a good idea is another question which depends on your design. – AllierType
tostring
dictionary, you need to know there'll be an exact match for the type of the object... see my answer for an alternative in the case where there might be subclassing though. – Biltong