Does typeof or is work when dealing with an interface?

  • Thread starter Thread starter Jim H
  • Start date Start date
J

Jim H

If I'm using DictionaryBase derived object lists and I iterate through them
with the IDictionary interface can I still check the object type by calling
typeof()?

btw I'm is using .NET 1.1

Thanks,
Jim

ex.
bool FindSpectialItem(string key, DictionaryBase[] MyDictionaryArray)
{
foreach(IDictionary dict in MyDictionaryArray)
{
bool found = false;
DerivedDictionaryA derivedDict = new DerivedDictionaryA ();

if(dict is DerivedDictionaryA) //or if(derivedDict.GetType() ==
typeof(DerivedDictionaryA))
{
//found a certain type
//look for key
found = true
}
else
continue;
}

return found;
}
 
Hi,

Of course, typeof ALWAYS return the type of the reference


--
Ignacio Machin
machin AT laceupsolutions com


| If I'm using DictionaryBase derived object lists and I iterate through
them
| with the IDictionary interface can I still check the object type by
calling
| typeof()?
|
| btw I'm is using .NET 1.1
|
| Thanks,
| Jim
|
| ex.
| bool FindSpectialItem(string key, DictionaryBase[] MyDictionaryArray)
| {
| foreach(IDictionary dict in MyDictionaryArray)
| {
| bool found = false;
| DerivedDictionaryA derivedDict = new DerivedDictionaryA ();
|
| if(dict is DerivedDictionaryA) //or if(derivedDict.GetType() ==
| typeof(DerivedDictionaryA))
| {
| //found a certain type
| //look for key
| found = true
| }
| else
| continue;
| }
|
| return found;
| }
|
|
 
Hello Jim,

Yes, you can use typeof to get Type instance from both class type or
interface, interface is just one of the .NET object types. Also, another
means to check whether an object is of a given type (in C#) is using the
"as" operator:

TypeName typedobj = UncastedObject as TypeName;

if(typedobj != null)
{

...........

}

Hope this also helps.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead



This posting is provided "AS IS" with no warranties, and confers no rights.
 
if(dict is DerivedDictionaryA) //or if(derivedDict.GetType() ==
typeof(DerivedDictionaryA))

Be aware, however, that the two tests do different things.

Assuming that DerivedDictionaryA is a class, then:

dict is DerivedDictionaryA

will be true if dict is a DerivedDictionaryA or any class derived from
DerivedDictionaryA.

dict.GetType() == typeof(DerivedDictionaryA)

will be true only if dict is a DerivedDictionaryA.
 
Back
Top