473,383 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

casting problems in c#

Hi !

I hope somebody can help me, i'm completly out of mind.
My problem:

I have a class inherited from Windows.Forms.Control named BasicModule,
which implements an interface named IModule (this has nothing to do
with the Module-Class of the framework. it's selfmade).

Now when I instantiate an object dynamically from an assembly created
from the source of BasicModule, i'm able to cast this object to
Control, but not to IModule, not even to BasicModule.

so that you can imagine something:

public class BasicModule : Control, IModule
{ ... }

public interface IModule
{ ... }

now the critical part:

ModuleEntity selected = (ModuleEntity)trvQueries.SelectedNode.Tag;
object instance = selected.Library.CreateInstance("DAP." +
selected.Description.Class,true);
pnlModule.Controls.Add((Control)instance);
((IModule)instance).DBConnection = dbConnection;

ModuleEntity holds information about the loaded assembly (stored in
member "Library", "DAP" is namespace of project)
pnlModule is a panel to which i want to add the control

it just doesn't work !
the debugger even tells me, that "instance" is of type BasicModule,
but i'm not able to cast it to this class
i also tried to make a abstract base-class, which inherits Controls
and implements IModule
and inherit BasicModule from this base-class
but i also can't cast to that abstract base-class !

i'm freaking out

please help me, i'm in serious trouble if i don't solve the problem
soon
ps: it's an requirement, that i can load any assembly-class, which
implements the IModule interface, at runtime
this is the base of an extensible application which loads specific
dlls described in some xml-configuration-file
so you don't have to rebuild the application when adding new modules
Jul 19 '05 #1
2 3760
Jon Skeet <sk***@pobox.com> wrote in message news:<MP************************@news.microsoft.co m>...
Simon X-Session <x-*******@gmx.at> wrote:

<snip>
it just doesn't work !
the debugger even tells me, that "instance" is of type BasicModule,
but i'm not able to cast it to this class


This usually happens if you've got the base class/interface present in
two different assemblies - the dynamically loaded one and the
"driving" one. Put it in just one place, and you should be fine.


i don't know if i understand you right
i need to have the interface in both assemblys, otherwise it wouldn't
compile

well, i coded a little sample program to demonstrate my problem:
(BaseClass.cs)
namespace CastTest
{
public class BaseClass
{
private int x;
public BaseClass()
{
x = 0;
}
public int X
{
set { x = value; }
get { return x; }
}
}
}

(ITest.cs)
namespace CastTest
{
public interface ITest
{
int Square();
}
}

(TestClass.cs)
namespace
{
public class TestClass : BaseClass, ITest
{
public TestClass()
{
X = 5;
}
public int Square()
{
return X*X;
}
}
}
first: test it with normal object instantiation (CastTest.cs)

(Test.cs)
namespace CastTest
{
public class MainClass
{
public static void Main(string[] args)
{
try
{
object instance = new CastTest.TestClass();
int x = ((CastTest.ITest)instance).Square();
// just a test, cast to TestClass
int y = ((CastTest.TestClass)instance).Square();
System.Console.Write("x ok: " + x);
System.Console.Write("\ny ok: " + y);
}
catch (System.Exception e)
{
System.Console.Write(e.Message);
}
}
}
}

compiles and runs fine

second: test it with loading assembly (Test.cs)

(Test2.cs)
namespace CastTest
{
public class MainClass
{
public static void Main(string[] args)
{
try
{
System.Reflection.Assembly as =
System.Reflection.Assembly.LoadFrom("CastTest.dll" );
System.Console.Write("Assembly loaded: " +
as.ToString());
object instance =
as.CreateInstance("CastTest.TestClass");
System.Console.Write("Instance created: " +
instance.ToString());
int x = ((CastTest.ITest)instance).Square();
int y = ((CastTest.TestClass)instance).Square();
System.Console.Write(x);
}
catch (System.Exception e)
{
System.Console.Write("\n" + e.Message);
}
}
}
}

i compile the base classes to a library
..\>csc /target:library /out:CastTest.dll BaseClass.cs ITest.cs
TestClass.cs

and compile main class including other cs-file (otherwise it doesn't
compile cause he doesn't know ITest)
..\>csc Test.cs ITest.cs

loading of assembly and instatiation of class works flawlessly, but as
soon as i want to cast the object reference to the interface, it fails
drop the line where i cast to the interface and uncomment the test to
cast to "TestClass"
even this fails in runtime
notive the output of ToString() of instance
it says CastTest.TestClass !!
so this class should be save to be casted
Jul 19 '05 #2
Simon X-Session <x-*******@gmx.at> wrote:
This usually happens if you've got the base class/interface present in
two different assemblies - the dynamically loaded one and the
"driving" one. Put it in just one place, and you should be fine.
i don't know if i understand you right
i need to have the interface in both assemblys, otherwise it wouldn't
compile


No you don't. You need to add a reference to the assembly which
contains the interface in order to compile against it.

You may well decide to put the interface in a separate (and thus very
small) assembly on its own, and add a reference to that assembly for
both of the other assemblies.

<snip>
loading of assembly and instatiation of class works flawlessly, but as
soon as i want to cast the object reference to the interface, it fails
drop the line where i cast to the interface and uncomment the test to
cast to "TestClass"
even this fails in runtime
notive the output of ToString() of instance
it says CastTest.TestClass !!
so this class should be save to be casted


No it shouldn't - because if you output GetType()==typeof(ITest) you'll
find they're not the same types. Basically you end up with two separate
types in memory, both for the same type name. The cast is using the
version loaded in its assembly, but the actual type is the one in the
assembly containing the test class.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Ying Yang | last post by:
Hi, How to I make pointers of different object types point to each other? <snippet> Node2* link2; Node1* link1; link1 = link2 //error
2
by: ghostdog | last post by:
hi, i got this opengl/c++ code: <code> void render(CMesh *mesh){ ... float *pVertices; int *pIndices;
4
by: David Rager | last post by:
Howdy, Put briefly, I have an array of chars, which I would like to access in pairs of bytes via casting the array to an array of shorts. I'm trying to be as elegant as possible. Below is a...
3
by: Andy Lomax | last post by:
I'm using a library where the supplier has provided base class 'foo', and a reference counting class which wraps 'foo': ------------------- library code ----------------------- template<class T>...
231
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought...
2
by: MackS | last post by:
In C89 can I safely do the following void function(void *p) { FILE *fp = p; /* ... */ return; }
5
by: JS | last post by:
I give a function a void pointer as an argument. But in the function I would like to treat this argument as an integer (only pointers to integers will be sent to the function) therefor I would like...
8
by: Quinn Kirsch | last post by:
Hi all, the following c# example baffles me. my understanding of the managed code of visual .net is that all casts like this would be safe, but this example seems to contradict this notion. if...
5
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have...
101
by: Tinkertim | last post by:
Hi, I have often wondered if casting the return value of malloc() (or friends) actually helps anything, recent threads here suggest that it does not .. so I hope to find out. For instance : ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.