473,383 Members | 1,877 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.

Recasting object from a variable or type object.

I have a custom class that has been assigned to a variable and worked with, I
now need to cast this class as a different class, which is in a separate
assembly, not currently in the project. Normally if it was part of the
project I would say:

MyNewClass newClassObject = (MyNewClass) currentClassObject;

I have the name of the class, assembly and namespace in separate variables.
I even have a variable of ‘Type’ that is equal to ‘MyNewClass’ (from below
code)

string stuffToLoad = myNameSpace + "." + myClass + ", " + myAssembly;
Type myType = Type.GetType(stuffToLoad, true);

My problem is that I need to recast currentClassObject into MyNewClass and
I seem to have run out of options. Have tried several roads already. Anyone
have any ideas?

-phil

Nov 17 '05 #1
9 5389
I just don't understand, if you have a reference to the assembly, you
should be able to do something the same as if the case is valid :
MyNewClass newClassObject = (MyNewClass) currentClassObject;
Maybe I miss your point.

Jianwei

Phil wrote: I have a custom class that has been assigned to a variable and worked with, I
now need to cast this class as a different class, which is in a separate
assembly, not currently in the project. Normally if it was part of the
project I would say:

MyNewClass newClassObject = (MyNewClass) currentClassObject;

I have the name of the class, assembly and namespace in separate variables.
I even have a variable of ‘Type’ that is equal to ‘MyNewClass’ (from below
code)

string stuffToLoad = myNameSpace + "." + myClass + ", " + myAssembly;
Type myType = Type.GetType(stuffToLoad, true);

My problem is that I need to recast currentClassObject into MyNewClass and
I seem to have run out of options. Have tried several roads already. Anyone
have any ideas?

-phil

Nov 17 '05 #2
"Jianwei Sun" wrote:
I just don't understand, if you have a reference to the assembly, you
should be able to do something the same as if the case is valid :


Perhaps that is my problem, that it is too simple <w>. I’ve only been
working in C# for about six months so it is still new to me.

// Set Assembly Filename
string assemblyFileName = String.Concat(GetAppPath(), myAssembly, ".dll");
// Create Assembly
Assembly a = Assembly.LoadFrom(assemblyFileName);

MyNewClass newClassObject = (MyNewClass) currentClassObject;

---

Using the above reference to the proper assembly how do I recast as above?
I tried:

typeof(a.gettype(myClass) newClassObject = (typeof(a.gettype(myClass))
currentClassObject;

and several other variations…

Nov 17 '05 #3
Phil <Ph**@discussions.microsoft.com> wrote:
I have a custom class that has been assigned to a variable and worked with, I
now need to cast this class as a different class, which is in a separate
assembly, not currently in the project. Normally if it was part of the
project I would say:

MyNewClass newClassObject = (MyNewClass) currentClassObject;

I have the name of the class, assembly and namespace in separate variables.
I even have a variable of ?Type? that is equal to ?MyNewClass? (from below
code)

string stuffToLoad = myNameSpace + "." + myClass + ", " + myAssembly;
Type myType = Type.GetType(stuffToLoad, true);

My problem is that I need to recast currentClassObject into MyNewClass and
I seem to have run out of options. Have tried several roads already. Anyone
have any ideas?


Well, why do you want to cast? Presumably it's to use a member of the
type - if you know the member at compile time, how come you don't know
the actual type? The usual answer here is that you know some interface
that the type implements, and you only need to call a member in that
interface - in which case, just cast to the interface.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #4
"Jon Skeet [C# MVP]" wrote:
Well, why do you want to cast? Presumably it's to use a member of the
type - if you know the member at compile time, how come you don't know
the actual type? The usual answer here is that you know some interface
that the type implements, and you only need to call a member in that
interface - in which case, just cast to the interface.


Yes, I use a factory to create instances of classes that are not in my
project. I use an interface to get at them, but the current interface does
not contain a reference to a variable I need. Therefore I would like to get
access to the derived class by recasting it.

I tried: Convert.ChangeType(currentObject, myNewType);

and this does correctly recast the object, however my code then has no idea
that I understand the object and fails when I try to use a method or variable
on it. That is:
currentObject.methodOfMyNewType; // This fails to compile

This seems to make me think that the method I'm try to accomplish here may
not bear fruit either. Seems like I need to make my code understand I really
do understand it.

Nov 17 '05 #5
Phil <Ph**@discussions.microsoft.com> wrote:
"Jon Skeet [C# MVP]" wrote:
Well, why do you want to cast? Presumably it's to use a member of the
type - if you know the member at compile time, how come you don't know
the actual type? The usual answer here is that you know some interface
that the type implements, and you only need to call a member in that
interface - in which case, just cast to the interface.


Yes, I use a factory to create instances of classes that are not in my
project. I use an interface to get at them, but the current interface does
not contain a reference to a variable I need. Therefore I would like to get
access to the derived class by recasting it.

I tried: Convert.ChangeType(currentObject, myNewType);

and this does correctly recast the object, however my code then has no idea
that I understand the object and fails when I try to use a method or variable
on it. That is:
currentObject.methodOfMyNewType; // This fails to compile

This seems to make me think that the method I'm try to accomplish here may
not bear fruit either. Seems like I need to make my code understand I really
do understand it.


I don't understand why you don't just cast to the actual type. If the
compiler has to know about the type anyway (in order to compile the
last line above), why can't it know about it to compile it?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
> I don't understand why you don't just cast to the actual type. If the
compiler has to know about the type anyway (in order to compile the
last line above), why can't it know about it to compile it?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet


The entire purpose I'm doing this is so that there is NO reference to the
assembly I'm trying to cast it to. That is why I use a Factory to create the
object in the first place. My question is simply, is there a way to do this:

NewClass myNewObject = (NewClass) myOldObject ;

where all I have is the previously mentioned info. It seems that:

Convert.ChangeType(currentObject, myType);

does the same thing, but when I try and use any methods of the myType class
since it does not have prior knowledge of its methods, it will not allow me
to compile.

-phil


Nov 17 '05 #7
"Phil" wrote:

The entire purpose I'm doing this is so that there is NO reference to the
assembly I'm trying to cast it to.
which is a pointless thing to do. because regardless whether you have a
hard reference at compile time or not, at runtime, that assembly will HAVE TO
be loaded if you want to execute any code in it.
That is why I use a Factory to create the
object in the first place.
If you are using a factory, then you should limit everything you access to
be defined in a common interface. otherwise the whole factory pattern is
kinda pointless.
My question is simply, is there a way to do this:

NewClass myNewObject = (NewClass) myOldObject ;

where all I have is the previously mentioned info.


there is no way to do dynamic cast at runtime because casting is a compile
time concept. to achieve what you want, you need to make late-bound calls
through reflection. however, I still find your requirement a bit strange.
maybe I'm missing something.
Nov 17 '05 #8
*** Here is one solution, note that this only allows use of a single field
and not exsposure of the object that was desired. The field I wanted was a
'SortedList' type. ***

Keep in mind that myObject started out as the concrete class, and was
converted to the derived class which has the unexposed fields. The converted
derived class is then scanned for the desired field and set according. Not
exactly desired effect but still it gave me the data I needed.

string stuffToLoad = myNameSpace + "." + myClass + ", " + myAssembly;
Type myType = Type.GetType(stuffToLoad, true);

Convert.ChangeType(myObject, myType);

// List the members of theClass
BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;

Type type = myObject.GetType();
foreach (FieldInfo fieldInfo in type.GetFields (myBindingFlags))
{
string nam = fieldInfo.Name;
if (nam == "sections")
{
sourceSections = (SortedList) fieldInfo.GetValue(myObject);
}
}

-Phil Fischer

Nov 17 '05 #9
Phil <Ph**@discussions.microsoft.com> wrote:
*** Here is one solution, note that this only allows use of a single field
and not exsposure of the object that was desired. The field I wanted was a
'SortedList' type. ***

Keep in mind that myObject started out as the concrete class, and was
converted to the derived class which has the unexposed fields. The converted
derived class is then scanned for the desired field and set according. Not
exactly desired effect but still it gave me the data I needed.


You don't actually need to scan through all the fields - you can just
call GetField with the appropriate field name.

It would be far better to encapuslate the extra field (preferrably as a
property) in a another interface.

Do you *actually* need to change the type, by the way? Does the
originally created type not contain the field, or were you just trying
to cast?

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

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

Similar topics

3
by: william | last post by:
Hi everyone, I just started learning VB.NET, I found there are a lots methods passing object parameter by value. For example, Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As...
4
by: kamran | last post by:
Hi I was wondering if it is possible to recast a pointer in C ? What I mean in detail is that I have compressed data coming from an instrument. These are mostly sample differences from the...
100
by: E. Robert Tisdale | last post by:
What is an object? Where did this term come from? Does it have any relation to the objects in "object oriented programming"?
26
by: yb | last post by:
Hi, Is there a standard for the global 'window' object in browsers? For example, it supports methods such as setInterval and clearInterval, and several others. I know that w3c standardized...
12
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. ...
7
by: Arpan | last post by:
The .NET Framework 2.0 documentation states that An Object variable always holds a pointer to the data, never the data itself. Now w.r.t. the following ASP.NET code snippet, can someone please...
9
by: Alexander Widera | last post by:
hi, is it possible to return an object of an unknown (but not really unknown) type with an method? i have the following situation: - a variable (A) of the type "object" which contains the...
21
by: phpCodeHead | last post by:
Code which should allow my constructor to accept arguments: <?php class Person { function __construct($name) { $this->name = $name; } function getName()
23
by: Hugh Oxford | last post by:
How do I get an object's name? EG. $obj_FOO = new Bar; echo $obj_FOO->getName(); 'obj_FOO'
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: 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.