Finding Base Types dynamically

My apologies if this was posted twice. I couldn't get it to post the first time, so I tried again.

I'm guessing I am just doing something wrong, because I don't see how it is possible for .NET to not include this feature. I have a base abstract class, Shape, with many different inherited Shape Types. All Shape Types inherit from the base abstract class, Shape, and are all (including Shape) located under the Shapes namespace.

"value" is a type parameter which is passed into a method. Say for example, value is of type "Shapes.ExtrudedCircle" The following if statement doesn't work as I expected:

if (value == typeof(Shapes.Shape))
{
Shape so = (Shape)value; // Doesn't go into this if statement:(

return so;
}


However, this will:

if (value == typeof(Shapes.ExtrudedCircle))
{
Shape so = (Shape)value; // Success, but is not what I need:(

return so;
}


Any ideas what I'm doing wrong Shouldn't .NET understand that ExtrudedCircle is still of the Shape Type




Answer this question

Finding Base Types dynamically

  • Inaki Ayucar

    Excellent, thank you:)


  • domw001

    You are doing type equality rather than equivalence. What you want to be able to do is determine if some type is either a specific type or derived from it. You can't use == for that. Instead, since you have the type, you should use the IsSubclassOf method.

    public class Shape {}
    public class Circle : Shape {}
    public class Triangle : Shape {}
    public class Rectangle : Shape {}

    class Program
    {
    static void PrintShape ( Type type )
    {
    if (type.IsSubclassOf(typeof(Shape)) || (type == typeof(Shape)))
    Console.WriteLine("Is a shape");
    if (type.IsSubclassOf(typeof(Circle)) || (type == typeof(Circle)))
    Console.WriteLine("Is a circle");
    if (type.IsSubclassOf(typeof(Triangle)) || (type == typeof(Triangle)))
    Console.WriteLine("Is a Triangle");
    if (type.IsSubclassOf(typeof(Rectangle)) || (type == typeof(Rectangle)))
    Console.WriteLine("Is a Rectangle");
    }

    static void PrintShape ( Shape shape )
    {
    if (shape is Shape)
    Console.WriteLine("Is a shape");
    if (shape is Circle)
    Console.WriteLine("Is a circle");
    if (shape is Triangle)
    Console.WriteLine("Is a Triangle");
    if (shape is Rectangle)
    Console.WriteLine("Is a Rectangle");
    }

    static void Main ( string[] args )
    {
    Rectangle rect = new Rectangle();
    PrintShape(rect.GetType());
    }
    }

    For comparison the second version of PrintShape doesn't use the type at all but rather uses the is operator to distinguish. It is the superior method to use when possible rather than dealing with types directly.

    Michael Taylor - 8/2/06


  • Finding Base Types dynamically