Determine type of inherited class

M

Magnus

i have a class which inherits from a base class

class base1 {
}

class child1 : base1 {
}

how can I determine if child1 is of base1? gettype returns type of child1,
but I need to know the type of the class inherited from, the base class.
Casting will cause an exception if the base class is of the wrong type, I
would like to avoid any exception approach.

I basically would like to know if I can cast the object to one or the other
type. Any ideas?

Thank you.

- Magnus
 
A

Alan Pretre

Magnus said:
how can I determine if child1 is of base1? gettype returns type of child1,
but I need to know the type of the class inherited from, the base class.
Casting will cause an exception if the base class is of the wrong type, I
would like to avoid any exception approach.

if (obj is base1) ...

-- Alan
 
B

Brian Gideon

Magnus,

The 'is' and 'as' operators will do just that. The 'is' operator
evaluates to a bool. The 'as' operator returns a reference of the type
specified or null if the object is not of the specified type.

// Example 1
if (myClass is base1)
{
// whatever
}

// Example 2
base1 myBaseClass = myClass as base1;
if (myBaseClass != null)
{
// whatever
}

Brian
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You can use Type.BaseType:

instance.GetType().BaseType

You could also use "is" or "as" if all you want to do is a test
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top