Lijo Lijo - 1 month ago 8
C# Question

How to check whether a base class object or derived object?

I have a

BankAccount
class.
FixedBankAccount
and
SavingsBankAccount
are derived from it.

I need to throw an exception if the recieved object is not a derived object. I have the following code.

IEnumerable<DBML_Project.BankAccount> accounts = AccountRepository.GetAllAccountsForUser(userId);
foreach (DBML_Project.BankAccount acc in accounts)
{
string typeResult = Convert.ToString(acc.GetType());
string baseValue = Convert.ToString(typeof(DBML_Project.BankAccount));

if (String.Equals(typeResult, baseValue))
{
throw new Exception("Not correct derived type");
}
}

namespace DBML_Project
{

public partial class BankAccount
{
// Define the domain behaviors
public virtual void Freeze()
{
// Do nothing
}
}

public class FixedBankAccount : BankAccount
{
public override void Freeze()
{
this.Status = "FrozenFA";
}
}

public class SavingsBankAccount : BankAccount
{
public override void Freeze()
{
this.Status = "FrozenSB";
}
}

} // namespace DBML_Project


Is there any better code than this?

Answer

I would define an interface (something like IAccettableBankAccount, but you know your domain, so you should be able to find a better name) and have FixedBankAccount and SavingsBankAccount implement it. Then your test would simply be:

if (!acc is IAccettableBankAccount)
{
     throw new Exception("Not correct derived type");
}
Comments