473,698 Members | 2,005 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reflection / casting

cv
Hi, I want to create an object from a class I load from an assembly.
Then I want to cast that object to a class (an interface) 'known' to the
program in order to pass it to other methods that work with that interface.

The casting is invalid but I can't see why, as the class I load from the
assembly really is of the type I cast it to.

Command a = (Command) t.GetConstructo r(new
Type[0]).Invoke(System .Reflection.Bin dingFlags.Publi c,null,null,nul l);

What can be the cause of the cast being invalid? I tried to cast it to
almost everything that might be possible. I didn't find any examples on
the Internet that do really cast the object.
I know I can invoke a method on the returned object by using Invoke(..
but that's not really the purpose.

Maybe somewhat clearer:

ConstructorInfo ci = t.GetConstructo r(new Type[0]);
object o = ci.Invoke(Syste m.Reflection.Bi ndingFlags.Publ ic,null,null,nu ll);
Command a = (Command) o;

-> Invalid cast exception

t.FullName
-> program.shell.t extualshell.com mands.command

Type tt = o.getType();
tt.FullName
-> program.shell.t extualshell.com mands.command

I'm totally in the dark here..
Please do not hesitate to ask additional information if necessary.
Thanks in advance.
Nov 16 '05 #1
2 6376
Ok, here's your checklist:
- You have a declared interface in an assembly
- The class you are trying to create by reflection implements that interface
(i.e. has a declaration like: public class Whatever : IMyInterface)
- The very same interface (same assembly it's declared in) is referenced in
the program creating the object via reflection, and that is the interface
you try to cast it to.

If all these things are true then you class should be castable to the known
interface. If however, for example, your class has methods that match a
declared interface, but it does not explictly implement the interface, you
cannot cast it. In that case you will have to use delegates or reflection
to invoke the methods.

Richard
--
C#, .NET and Complex Adaptive Systems:
http://blogs.geekdojo.net/Richard
"cv" <vo************ ******@cv-soft.com> wrote in message
news:10******** *******@seven.k ulnet.kuleuven. ac.be...
Hi, I want to create an object from a class I load from an assembly. Then
I want to cast that object to a class (an interface) 'known' to the
program in order to pass it to other methods that work with that
interface.

The casting is invalid but I can't see why, as the class I load from the
assembly really is of the type I cast it to.

Command a = (Command) t.GetConstructo r(new
Type[0]).Invoke(System .Reflection.Bin dingFlags.Publi c,null,null,nul l);

What can be the cause of the cast being invalid? I tried to cast it to
almost everything that might be possible. I didn't find any examples on
the Internet that do really cast the object.
I know I can invoke a method on the returned object by using Invoke(.. but
that's not really the purpose.

Maybe somewhat clearer:

ConstructorInfo ci = t.GetConstructo r(new Type[0]);
object o =
ci.Invoke(Syste m.Reflection.Bi ndingFlags.Publ ic,null,null,nu ll);
Command a = (Command) o;

-> Invalid cast exception

t.FullName
-> program.shell.t extualshell.com mands.command

Type tt = o.getType();
tt.FullName
-> program.shell.t extualshell.com mands.command

I'm totally in the dark here..
Please do not hesitate to ask additional information if necessary.
Thanks in advance.

Nov 16 '05 #2
cv <vo************ ******@cv-soft.com> wrote:
Hi, I want to create an object from a class I load from an assembly.
Then I want to cast that object to a class (an interface) 'known' to the
program in order to pass it to other methods that work with that interface.


Sounds like your problem is the one in
http://www.pobox.com/~skeet/csharp/plugin.html

If it isn't, could you post a short but complete program which
demonstrates the problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

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

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

Similar topics

2
1786
by: Angelos Karantzalis | last post by:
Hi guys, I'm trying to load a class instance dynamically, and then cast it to it's base type so I can use it in my app. More specifically, I'm dynamically instantiating a System.Web.UI.WebControls.RequiredFieldValidator and attempting to cast it into an IValidator and/or a BaseValidator. Both casting attempts have failed miserably, throwing an InvalidCastException ... how can it be i cannot cast to the base class of my instance ???
1
2621
by: Mike Malter | last post by:
I am just starting to work with reflection and I want to create a log that saves relevant information if a method call fails so I can call that method again later using reflection. I am experimenting a bit with what I need to do this and have the following code snippet. But first if I pass the assembly name and type to Activator.CreateInstance() it always fails. However if I walk my assembly and get a type value, the call to...
1
1692
by: Roman Muntyanu | last post by:
Hi all, I created object of MyClass : ISomeInterface Then I created object of this class using reflection mechanism. ISomeInterface instance = (ISomeInterface)constructorInfo.Invoke(new Object ); This casting works fine. But When I try
2
2983
by: Robert W. | last post by:
I'm trying to write a utility that will use Reflection to examine any data model I pass it and correctly map out this model into a tree structure. When I say "any" , in fact there will only be 3 types of items in the very hierarchical data model: - Classes (and nested classes) - Collections - Properties I've successfully written the Reflection code to handle any combination of classes and properties but I'm confused about what to do...
7
2362
by: Paul Hadfield | last post by:
Hi, I'm running into one problem with trying to call "Type.GetCustomAttributes(...)" on my reflected code. Basically - I can't trap my own custom attribute - I can only catch / identify system "Custom Attributes" by type. The output below identifies that I can catch the "DefaultMemberAttribute", but I can not catch my own "DirectoryVersionAttribute". Cany anyone throw any light on this as it is driving mad Thanks in Advance, - Paul....
9
3846
by: Kuberan Naganathan | last post by:
Hello all Does anyone know of a good way to use reflection in c++? I don't mean simply using rtti or dynamic casting. I'm talking about java/c# style reflection where an actual instance of an object can be constructed through reflection and method calls can be made via the reflection apis.
5
1859
by: | last post by:
I am having problems with casting or converting a class to to an interface from which it derives. I'm certain that it's due to how it's being loaded, but I'm not sure how to get past the problem. Here's a general outline of the architecture. It's oversimplified, but I think it's enough info to help: Assembly A.dll { interface IMyBase {}
11
6398
by: =?Utf-8?B?dG9iaXdhbl9rZW5vYmk=?= | last post by:
The following code is in a custom deserializer: object value = (int) 1; string nameToParse = Enum.GetName(field.FieldType, value); value = Enum.Parse(field.FieldType, nameToParse); Currently we follow the path below: intValue --enum name --enum value
5
4298
by: Klaudiusz Bryja | last post by:
Hi, This is for NetCF 2.0. I need to create event handling code which using reflection. I have some parameters in XML which describe how event should be handled. I have code to create delegate: public class DelegateEx {
0
9016
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8887
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6515
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5858
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4360
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4613
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2321
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1997
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.