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?
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.
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.
In C++, a derived class object can be assigned to a base class object, but the other way is not possible.
No. A reference to a derived class must actually refer to an instance of the derived class (or null).
You should be using Type.IsAssignableFrom
if (acc.GetType().IsAssignableFrom(typeof(BankAccount)))
// base class
else
// derived
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With