interface type casting help!

  • Thread starter Thread starter Richard Brown
  • Start date Start date
R

Richard Brown

I'm running into a big problem, and it's probably just my lack of C#
knowledge, but can someone give me a clue?

I'm using the folling object heirarchy:

AbstractViewContent -> Implements IViewContent interface
AbstractDatabaseView
TableEditorView
ProcedureEditorView
ViewEditorView

I have an implemented method call in a class ContentBinding,

IViewContent CreateViewContent(object obj)

that return TableEditorView, ProcedureEditorView or ViewEditorView depending
on the type of object.
(the IViewContent return type *cannot* be changed because it is part of a
library, I can only override the member method)

Now, in my other method,

void ObjectObject(AbstractDatabaseObject obj) {
ContentBinding binding = new ContentBinding();
AbstractDatabaseView content = (AbstractDatabaseView)
binding.CreateViewContent(obj);
content.Load(obj);
}

This compiles just fine, however, during runtime, I get an invalid type cast
exception on the second line!
Is it not possible to 'cast back down' from an implemented interface,
through the inheritance tree to a specifc child object?
I have traced the code, and, for the object I am trying to 'open', the
create view is TableEditorView.
 
Richard... I am afraid I really don't your understand the class
hiearchy,
_but_ if I needed to debug this I would add;

IViewContent content = binding.CreateViewContent(obj);
if (content is AbstractDataView) { // valid type and not null
... cast here
}
else {
.. alert here, or breakpoint here in debugger
}

http://www.geocities.com/jeff_louie/OOP/oop6.htm

Regards,
Jeff
This compiles just fine, however, during runtime, I get an invalid type
cast exception on the second line!<
 
Richard Brown said:
I'm running into a big problem, and it's probably just my lack of C#
knowledge, but can someone give me a clue?

<snip>

What you're doing should be fine, if CreateViewContent really *does*
return an AbstractDataView instance reference. However, if this is all
being done in a plug-in type scenario, you *may* be running into the
problem described at:

http://www.pobox.com/~skeet/csharp/plugin.html
 
Back
Top