Find the Type of a base class

How do I find out the type of a derived class's base class

now I do this but I dislike it

try{

myBase control = (myBase)derivedControl;

doStuff(control);

}

catch{}

I would like to do something like this

if(derivedControl.baseType() == typeof(myBase)

{

doStuff(derivedControl);

}

void doStuff(myBase control)

{

}




Answer this question

Find the Type of a base class

  • Hammo

    What you are looking for is the "is" and "as" syntax:

    you can do either:

    myBase control = derivedControl as myBase;
    if (myBase != null)
    {
      // derivedControl could be casted to myBase, do something with it
    }

     

    or you can use:

    if (derivedControl is myBase)
    {
      doStuff(derivedControl as myBase);
      // or cast it before the call, you choice...
    }

     

     

    -----
    if you really need to know the class type and what it is derived from, not only for casting purposes, you can use something like this to get the inhertance path:
    Type type = derivedControl.GetType();
    Console.WriteLine(type.FullName);
    while ((type = type.BaseType) != null) Console.WriteLine(type.FullName); 


  • milocat

    Figo

    Thank you this is exaclty what I was looking for. I just never thought about is and as.

    Brian



  • DaveSLC

    Hi, Brian

    We can use is keywords.

    Say Fox Class is derived from Mammal Class, then the instance of Fox is compatible to Mammal.

    For example:

    Class Fox: Mammal

    {...}

    Fox fox = new Fox();

    Mammal mammal = new Mammal();

    if(fox is Mammal)

    MessageBox.Show("fox is mammal's descendant ");

    else

    MessageBox.Show("fox is not mammal's descendant");

    Otherwise, to judge whether the class is directly derived from another you can:

    if (fox.GetType().BaseType == mammal.GetType())
    MessageBox.Show("fox is mammal's direct descendant ");
    else
    MessageBox.Show("fox is not mammal's direct descendant");

    see: http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=1255632&SiteID=1

    If you have further problem pls feel free to let me know.

    Thanks



  • Henning_ohm

    John,

    Thank you I never thought about the is and as syntax. This is exactly what I needed to do.

    Brian



  • Find the Type of a base class