Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

oop

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?

like image 791
LCJ Avatar asked Jul 03 '12 06:07

LCJ


People also ask

How do you identify a base class and a derived class?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.

How do you check if something is a certain type C++?

C++ has no direct method to check one object is an instance of some class type or not. In Java, we can get this kind of facility. In C++11, we can find one item called is_base_of<Base, T>. This will check if the given class is a base of the given object or not.

Can you assign a derived class object to a base class object?

In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

Can a derived class reference to base class object?

No. A reference to a derived class must actually refer to an instance of the derived class (or null).


1 Answers

You should be using Type.IsAssignableFrom

if (acc.GetType().IsAssignableFrom(typeof(BankAccount)))
    // base class
else
    // derived
like image 182
V4Vendetta Avatar answered Oct 21 '22 04:10

V4Vendetta