all groups > c# > february 2006 >
You're in the

c#

group:

Is there an easier or better way to compare Types?


Is there an easier or better way to compare Types? james
2/22/2006 7:36:26 PM
c#:
AssumeSomeFunctionExists ( Type someType, Type someOtherType)
{

// I want to know
// 1. Are the two the same Type
// 2. Are they members of the same Inheritance branch
// a) Is someType a subclassof someOtherType or
// b) Is someOtherType a subclass of someType
// This code does work but...

if ( someType.Equals(someOtherType) ||
someType.IsSubclassOf(someOtherType) || someOtherType.IsSubclassOf (
someType) )

// ... doSomething

}

Now I know about the "is" operator but that only works with an object
instance like

if ( anObject is SomeClass )

which does exactly what I want but I cannot use the "is" operator to compare
two Type objects

And I know about IsSubclass() but that does not return 'true' when the two
are exactly the same. So I
do what I show in the above code which takes three comparisons. Am I
missing a shortcut way to do this?

Thanks a lot in advance

JIM


Re: Is there an easier or better way to compare Types? Bob
2/23/2006 12:00:00 AM
Hi James,
I usually just work with the name property.
if (GetType(someType).Name="MyBase")



Don't know how efficient it is.

FWIW

Bob



[quoted text, click to view]

Re: Is there an easier or better way to compare Types? Jon Skeet [C# MVP]
2/23/2006 12:00:00 AM
[quoted text, click to view]

<snip>

[quoted text, click to view]

Have a look at Type.IsAssignableFrom. You'd just have to try it two
ways.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
Re: Is there an easier or better way to compare Types? james
2/23/2006 10:20:11 AM
That will tell me if they are equal, but nothing else unless I misunderstand
your answer

JIM

[quoted text, click to view]

Re: Is there an easier or better way to compare Types? james
2/23/2006 10:22:11 AM
Thanks Jon, I don't remember seeing that one before.. I'll give it a whirl


JIM


[quoted text, click to view]

AddThis Social Bookmark Button