[RESOLVED] Type equality...?
Hey,
I need to check if a certain Type instance:
1. Is equal to a type, and
2. Is equal to another type or derives from that type.
A little hard to explain, so let's bring in an example (actually, the real thing in this case as it's simple enough to understand).
I have one abstract class Shape, and many deriving classes, such as RectangleShape, EllipseShape, TriangleShape, etc.
Now, I need to check two different things:
Suppose I have a Type instance 't'. I need to check if
1. this type is exactly another type (such as RectangleShape). In english: "Is t a RectangleShape, but not some class deriving RectangleShape".
2. this type t is either one of the deriving Shapes (in english: "Does t derive from Shape?")
In code, I have a method that accepts a Type, and I need to check number 2 first (as a check whether the Type is actually a Shape, whatever Shape it is), and number 1 later (to check which kind of shape it actually is).
csharp Code:
private int GetNextFreeNumber(Type t)
{
if (t derives from Shape)
{
foreach (Shape s in this)
{
if (t is the type of s, and not a type deriving from s, nor any other Shape type)
{
//...
}
}
}
}
How do I do this? I know I can use
Code:
if (t == typeof(Shape))
and I also know of the 'is' operator, something like
Code:
if (someInstance is Shape)
but I can't use the 'is' operator because I haven't got an instance of Shape, I only got a Type (and that Type may be Button or Form or whatever, in which case I don't even need to do the foreach loop).
So basically I know of only one 'type equality' check in C#, but obviously I can't use it for both... Does my method do check number 1 or number 2, and how can I do the other check?
Googling for 'type equality' has turned out pretty useless, all I get is 'reference type equality' showing how to implement an IEquatable interface, and stuff like that.
Thanks!
Re: [RESOLVED] Type equality...?
hey,
about the IsSubclassOf, i just wanna share this
http://msdn.microsoft.com/en-us/libr...ubclassof.aspx