InvalidCastException with COM set methods
Hi All,
I am referring to an ActiveX dll in my windows project when i looked into metatdata there are some methods like say set_Test(ref object __MIDL_0543).
Now i want to set Test from my .net code, in vb code it is set as
Set objectName.Test = otherObject
With c# it is done like
object newObject = otherObject // otherObject is of type say Other
objectName.set_Test(ref newObject)
The above line throws then an InvalidCastException, so what should we do here.
Please suggest.
Thanks,
Anurodh
Re: InvalidCastException with COM set methods
Hi !
At first please reread forum usage and use codetags as we are not interested in reading code-sausage:D But without using codetags you will get unformatted code.
Code:
object newObject = otherObject // otherObject is of type say Other
objectName.set_Test(ref newObject)
In C# you need to declare the exact class if you want to use the object. You need to know which class newObject is before you are able to use it So you need to have knowledge about the dll before you are able to use it. Thas simple all about it.
Re: InvalidCastException with COM set methods
Thanks for the reply.
But it doesn't seems to be that simple. The real problem is the syntax generated by VS i.e. set_Test(ref object __MIDL_0543).
we have checked in the vb code that runs fine that it takes an object say ITest and Test implements ITest.
so, in c# we did it like:
Test t1 = new Test();
ITest t2 = t1;
object t3 = t2;
objectName.set_Test(ref t3); // throws invalidcastexception
Please suggest any solution on this.
Thanks,
Anurodh
Re: InvalidCastException with COM set methods
Quote:
Originally Posted by
anurodhora
so, in c# we did it like:
Code:
Test t1 = new Test();
ITest t2 = t1;
object t3 = t2; 'useless
objectName.set_Test(ref t3); // throws invalidcastexception
and what is objectname declared to be ? Does it have a set_Test method ?
There is nothing to suggest. this cannot be done that way in C# an object cannot ne used that way. Never, whatever it contains, you need to call it as the interface. Try
Code:
ITest t2 = new Test();// you can create a class and refer it directly by a pointer to its interface
objectName.set_Test(ref t2);
And please use CODETAGS
Re: InvalidCastException with COM set methods
I think that the class of the object beeing set (Test in your case) must be at least annotated with [ComVisible(true)] (or the whole assembly) and maybe it should implement some interface, which should be mentioned in reference.