473,385 Members | 1,492 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,385 software developers and data experts.

Using reflection to properly cast an object

How do I cast an object to its proper class at runtime given its System.Type
I have code that looks like this:

MyObject class has subclasses of MySubObjectA & MySubObjectB:
MyObject obja = new MySubObjectA ();
MyObject objb = new MySubObjectB ();

ArrayList list = new ArrayList();

list.Add(objb );
list.Add(obja );

ArrayList MyObjBs= GetAllOfType( typeof( MySubObjectB ) );
ArrayList MyObjAs = GetAllOfType( typeof( MySubObjectA ) );

public ArrayList GetAllOfType(System.Type t){
ArrayList result = new ArrayList();
foreach(object o in list){
Type objType = o.GetType();
if(objType.Equals(t))
result.Add( (t) o); //Doesn't compile
result.Add( o as t); //Doesn't compile
}
}

How do I get the objects properly casted to its class before I push em onto
my list? (I know that they are stored in the list as objects anyway, This
code isn't real, its purpose is only to express the question.)
Nov 16 '05 #1
5 19788
zfeld <zf******@hotmail.com> wrote:
How do I cast an object to its proper class at runtime given its System.Type
You can't - a cast is a compile-time concept.
I have code that looks like this:

MyObject class has subclasses of MySubObjectA & MySubObjectB:

MyObject obja = new MySubObjectA ();
MyObject objb = new MySubObjectB ();

ArrayList list = new ArrayList();

list.Add(objb );
list.Add(obja );

ArrayList MyObjBs= GetAllOfType( typeof( MySubObjectB ) );
ArrayList MyObjAs = GetAllOfType( typeof( MySubObjectA ) );

public ArrayList GetAllOfType(System.Type t){
ArrayList result = new ArrayList();
foreach(object o in list){
Type objType = o.GetType();
if(objType.Equals(t))
result.Add( (t) o); //Doesn't compile
result.Add( o as t); //Doesn't compile
}
}

How do I get the objects properly casted to its class before I push em onto
my list? (I know that they are stored in the list as objects anyway, This
code isn't real, its purpose is only to express the question.)


Casting them would have no effect. As you say, they're all just object
references as far as the list is concerned.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
zfeld wrote:
How do I cast an object to its proper class at runtime given its
System.Type I have code that looks like this:

MyObject class has subclasses of MySubObjectA & MySubObjectB:
MyObject obja = new MySubObjectA ();
MyObject objb = new MySubObjectB ();

ArrayList list = new ArrayList();

list.Add(objb );
list.Add(obja );

ArrayList MyObjBs= GetAllOfType( typeof( MySubObjectB ) );
ArrayList MyObjAs = GetAllOfType( typeof( MySubObjectA ) );

public ArrayList GetAllOfType(System.Type t){
ArrayList result = new ArrayList();
foreach(object o in list){
Type objType = o.GetType();
if(objType.Equals(t))
result.Add( (t) o); //Doesn't compile
result.Add( o as t); //Doesn't compile
}
}

How do I get the objects properly casted to its class before I push
em onto my list? (I know that they are stored in the list as objects
anyway, This code isn't real, its purpose is only to express the
question.)


It's not completely clear exactly what you want to do, so I may be wrong.
What exacly is the compile error you got?

The "ArrayList" holds only "object"s, so there is no use casting the object
you found to some type, before you put it in an ArrayList. Everything you
get out of an ArrayList is (first) reported as "object" anyway.

You can convert the ArrayList to a real array (MySubObjectB[]),
by using the ToArray method:
MySubObjectB[] msoba = (MySubObjectB [] )result.ToArray(typeof(MySubObjectB));

Did your check for the type work? Maybe you could try "if (o is t)"

Hans Kesting
Nov 16 '05 #3
Try your comparision as:

if(objType.Equals(typeof(t)))
{
.........
}
And when you say "doesn't compile" does it really not compile or does
it throw an exception?

Nov 16 '05 #4
You are looking at the wrong line of code:

if(objType.Equals(t)) - compiles fine.

It is either of the next 2 lines that don't compile

result.Add( (t) o); //Doesn't compile
result.Add( o as t); //Doesn't compile
I want to cast my generic object into the specific class using reflection or
the provided object type information.

"aa7im" <jo**@nautilusnet.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Try your comparision as:

if(objType.Equals(typeof(t)))
{
........
}
And when you say "doesn't compile" does it really not compile or does
it throw an exception?

Nov 16 '05 #5
I am facing The same Situation I also have to cast at runtime.
If any Body have sloved it then Please Help.

protected void Page_Load(object sender, EventArgs e)
{
Circle circleObj = new Circle();
circleObj.Radius = 5;
Response.Write(chkRefrence(circleObj)+"<br \\>");
}
private string chkRefrence(Shape shapeObject)
{
Type t = shapeObject.GetType();
//Response.Write(t.Name.ToString());//Here I am getting Circle
((t)shapeObject).Radius = 15;//I have to Cast here
shapeObject.Id = "TestObj ";
return shapeObject.ToString();
}
May 2 '06 #6

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

Similar topics

0
by: samlee | last post by:
Hi All, I'm learning how to write C# using reflection, but don't know how to code using reflection this.Controls.Add(this.label1); Could anyone help, Thank in advance. ...
7
by: maf | last post by:
Using reflection, I'm trying to get the value for a constant in an enum. Getting the contant name works fine using: FieldInfo fieldInfos = TYPE.GetFields(); foreach(FieldInfo fi in fieldInfos...
6
by: Joanna Carter \(TeamB\) | last post by:
Hi folks I have a Generic Value Type and I want to detect when the internal value changes. /////////////////////////////// public delegate void ValueTypeValidationHandler<T>(T oldValue, T...
3
by: tony lock | last post by:
I am writing a simulation program, the main classes inherit from a base class which itself inherits from Control. I am using reflection to serialize these objects including the fields from control....
3
by: trevorelbourne | last post by:
Hi, I am having trouble accessing the elements of an array using reflection. This is the code I am having trouble with: FieldInfo Fields = Obj.GetType().GetFields(); foreach (FieldInfo fi in...
1
by: Chad Silva | last post by:
Hi all I have an object created via reflection of type CateringObject.FBO. I'm trying to assign it to a property that accepts objects of type CateringObject.IDeliveryDestination (which is...
4
by: Søren M. Olesen | last post by:
Hi Is it (any way) possible using reflection to set an indicator (property, variable, attribute,..). on an object before it actually instantiated, so that this indicator can be used in the...
2
by: bill | last post by:
All, Can anyone supply an example or reference to an example of using reflection to determine the data types contained in a nested stucture in C#? Once I get the list of MemberInfo and determine...
4
by: =?Utf-8?B?QWJoaQ==?= | last post by:
I am using Reflection to invoke methods dynamically. I have got a special requirement where I need to pass a value to method by setting the custom method attribute. As I cannot change the...
1
by: =?Utf-8?B?U2NvdHQ=?= | last post by:
Hello, Using VS2008 in a C# web service application, a class has been created that inherits from the ConfigurationSelection. This class file has been placed in the App_Code folder. The...
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
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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.