LCJ
LCJ

Reputation: 22652

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?

Upvotes: 7

Views: 13757

Answers (5)

V4Vendetta
V4Vendetta

Reputation: 38210

You should be using Type.IsAssignableFrom

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

Upvotes: 12

Francesco Baruchelli
Francesco Baruchelli

Reputation: 7468

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");
}

Upvotes: 3

AksharRoop
AksharRoop

Reputation: 2293

Use Type.IsSubclassOf Method. For more info check this

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

Upvotes: 2

Botz3000
Botz3000

Reputation: 39610

You can just check the 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 the class as abstract might help, too, but i don't know if that's an option in your case.

Upvotes: 0

bhuvin
bhuvin

Reputation: 1402

Declare BankAccount class as Abstract.

Upvotes: 5

Related Questions