Checking an objects inheritance
-
In the following code pTable is of type CustomerTable, which inherits from DataTable. How can I change the "if" statement to check that pTable is derived from DataTable as the statement currently tests false, because the types are different. I thought I would cast ptable, but the of course that would throw an exception if that cast is invalid. if (pTable != typeof(DataTable)) { throw new EwGeneralException(lStk, EwExceptionID.DdlNotDataTable); } Many thanks for reading. Nursey
-
In the following code pTable is of type CustomerTable, which inherits from DataTable. How can I change the "if" statement to check that pTable is derived from DataTable as the statement currently tests false, because the types are different. I thought I would cast ptable, but the of course that would throw an exception if that cast is invalid. if (pTable != typeof(DataTable)) { throw new EwGeneralException(lStk, EwExceptionID.DdlNotDataTable); } Many thanks for reading. Nursey
-
In the following code pTable is of type CustomerTable, which inherits from DataTable. How can I change the "if" statement to check that pTable is derived from DataTable as the statement currently tests false, because the types are different. I thought I would cast ptable, but the of course that would throw an exception if that cast is invalid. if (pTable != typeof(DataTable)) { throw new EwGeneralException(lStk, EwExceptionID.DdlNotDataTable); } Many thanks for reading. Nursey
You're comparing apples and oranges, there.
pTable
is an instance, and thetypeof
operator will always return aType
, so the two would never match unlesspTable
was a variable which held aType
. If you want to check is something is an instance of a particular type, simply use theis
operator:if (pTable is DataTable)
{
// ...
}You can also use something like this, although it requires more code and more instructions (when compiled to IL):
if (pTable != null)
{
if (pTable.GetType() == typeof(DataTable))
{
// ...
}
}There's other ways of doing this, but you don't have to take inheritance into account. If
CustomerTable
inherits formDataTable
, then any instance is a type ofCustomerTable
,DataTable
,MarshalByValueComponent
, and - as with everything in .NET -Object
. It's also an instance of any interfaces that any classes up the inheritence hierarchy implement. This isn't true going down the hierarchy, though. For example, if you instantiate a new instance of aDataTable
, then it is not an instance of aCustomerTable
. Also keep in mind that it's not the declaration that counts, its the definition. For example:object o = new DataTable("Example");
While
o
is declared as anobject
, it's still an instance of aDataTable
. Callingo.GetType
will returnSystem.Data.DataTable
. This is polymorphism.Microsoft MVP, Visual C# My Articles