Home All Groups Group Topic Archive Search About

find out whether there already is an object of the same derived type in a generic collection

Author
23 Jun 2006 1:36 PM
Fabian
Hello,

I have a class hierarchy of "Task Activity" classes for a machine
control system. To manage the activities I have a dictionary class,
derived from Dictionary<string, TaskActivity>.
I have to check whether this dictionary (already) contains a
TaskActivity object of a specific type and - now it becomes difficult -
the mother class hierarchy.

If it was just the same Type my method below would work:

         public bool ContainsObjectOfType(Type ElementType)
         {
             foreach (TaskActivity activity in this.Values)
             {
                 if (activity.GetType() == ElementType)
                     return true;
             }
             return false;
         }

I e.g. call it via
bool result =
TaskActivityDictionary.ContainsObjectOfType(typeof(MotherClassOfTaskActivity));

activity.GetType() == ElementType    is only true if the object is of
exactly the same class but I need to know whether it is derived of the
mother class or the mother's mother class... (therefore
activity.GetType().BaseType doesn't work).

Is there another possibility of comparing types at runtime?

Cheers,

Fabian

Author
23 Jun 2006 2:04 PM
Markus Kling
The method you are searching for is Type.IsAssignableFrom
http://msdn2.microsoft.com/en-us/library/system.type.isassignablefrom.aspx.

Markus


Show quote
"Fabian" <neutronstorm@newsgroups.nospam> schrieb im Newsbeitrag
news:%23nViIoslGHA.4864@TK2MSFTNGP04.phx.gbl...
> Hello,
>
> I have a class hierarchy of "Task Activity" classes for a machine control
> system. To manage the activities I have a dictionary class, derived from
> Dictionary<string, TaskActivity>.
> I have to check whether this dictionary (already) contains a TaskActivity
> object of a specific type and - now it becomes difficult - the mother
> class hierarchy.
>
> If it was just the same Type my method below would work:
>
>         public bool ContainsObjectOfType(Type ElementType)
>         {
>             foreach (TaskActivity activity in this.Values)
>             {
>                 if (activity.GetType() == ElementType)
>                     return true;
>             }
>             return false;
>         }
>
> I e.g. call it via
> bool result =
> TaskActivityDictionary.ContainsObjectOfType(typeof(MotherClassOfTaskActivity));
>
> activity.GetType() == ElementType    is only true if the object is of
> exactly the same class but I need to know whether it is derived of the
> mother class or the mother's mother class... (therefore
> activity.GetType().BaseType doesn't work).
>
> Is there another possibility of comparing types at runtime?
>
> Cheers,
>
> Fabian

AddThis Social Bookmark Button