How to check if an object is a base class or a derived object?

I have a BankAccount class. FixedBankAccount and SavingsBankAccount derived from it.
I need to throw an exception if the resulting 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?

+4
source share
5 answers

I would define an interface (something like IAccettableBankAccount, but you know your domain so you can find a better name) and it can be used in FixedBankAccount and SavingsBankAccount. Then your test will be simple:

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

You should use Type.IsAssignableFrom

 if (acc.GetType().IsAssignableFrom(typeof(BankAccount))) // base class else // derived 
+9
source

Declare the BankAccount class as abstract.

+5
source

Use the Type.IsSubclassOf method. For more information check this.

 foreach (DBML_Project.BankAccount acc in accounts) { if (!acc.GetType().IsSubclassOf(typeof(DBML_Project.BankAccount)) { throw new Exception("Not correct derived type"); } } 
+2
source

You can simply check types directly:

  var accounts = AccountRepository.GetAllAccountsForUser(userId); if (accounts.Any(acc => acc.GetType() == typeof(DBML_Project.BankAccount))) { throw new Exception("Not correct derived type"); } 

Declaring a class as abstract can also help, but I don’t know if this option is in your case.

0
source

All Articles