I have the following example code. Waht is the best practice? Compare Values or compare Types to perform a certain business logic:
public Customer
{
public Category {get;set;}
public CategoryName {get;set;} //e.g. "Category A" or "Category B"
}
public Category{}
public CategoryA : Category {}
public CategoryB : Category {}
public void Main()
{
Customer customer = new Customer();
// Option 1:
if(customer.CategoryName == "Category A")
{
CategoryA catA= customer.Category as CategoryA;
DoSomething(catA)
}
// Option 2:
CategoryA catA= customer.Category as CategoryA;
if(catA != null)
{
DoSomething(catA)
}
// Option 3:
if(customer.Catgeory is Category A)
{
CatgeoryA catA= customer.Category as CategoryA;
DoSomething(catA)
}
}
The Code is just for illustration.
Given those 3 options, I’d go with Option 2.
e.g. – Try to make a conversion and check if it isn’t
Null.The reason it is better then the last option is that Option 3 causes you to make 2 conversions, one for the
isand one for theasin the next line.Finally, Option 1 is the worst IMO – it requires you to have some kind of logic that you can’t really be sure will stick later on (No one is preventing someone from creating a customer with a
Categoryof CategoryA and aCategoryNameof “Category B”). Also, this is additional logic which can be done in a much clearer way via Option 2.I should mention, as pointed out in the other comments/answers, there are a few more options that can be taken into account. Using Polymorphism is probably the best design strategy.