Simon Woods wrote:
I have an object which is implementing a secondary interface. I want to
get the name of the underlying object.
"Name" or "Type"?
name = DirectCast(myInterfacedObject, Object).GetType.Name
Are there better ways of doing this? Examples I've seen in C# seem to
suggest that you can call the GetType off the Interface itself.
You /should/ be able to.
The only thing to watch out for is some "bright-spark" may have
Shadow'ed the GetType method and made it do something completely
different - stupid, I know, but it's the kind of thing Developers /love/
to do - "up-casting" to Object gets around this by using Object's most
basic implementation.
Obviously I could put the Name property onto the interface, but I'm
wondering if there are some other ways I could do this?
If you're after a Name property on a class that you know about, just
cast the reference to the required Type (after checking that you /can/,
of course):
If TypeOf myInterfacedObject Is NamedThing Then
sName = DirectCast( myInterfacedObject, NamedThing ).Name
End If
Also, what is going on when DirectCast is called? Is the object being
copied to somewhere else in memory or is a different address in memory
being used to retrieve the Type info?
Nope. If you've ever worked with 'C++' or 'C#', you'll have come across
the likes of:
int * pointerToInteger = 0 ;
char * pointerToChar = (char *)pointerToInteger ;
The second line takes a pointer to an integer value and blithely stuffs
it into a variable that's supposed to point to a character value. Both
pointers refer to the same chunk of memory, but treat it as different
"types".
DirectCast does much the same thing. It tells the compiler to treat the
given "object reference" (a.k.a. strongly-typed Pointer) as a reference
to a /different/ Type. However, it does go a little bit further and
checks the object's inheritance hierarchy and, if it can't make the cast
you've asked it to, it'll throw an Exception on you:
Class Class1
Public Property Name
Class Class2 Inherits Class1
Class Class3 Inherits Class2
Class Class4
Dim c2 as New Class2
?DirectCast( c2, Class1 ).Name ' OK
?DirectCast( c2, Class4 ).Name ' Boom!
?DirectCast( c2, Class3 ).Name ' Boom! Think about this one
HTH,
Phill W.