473,881 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confused about using Reflection to examine a collection

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" [data model], 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 when I encounter a
collection. Here's some starting code I've written:

-----------------------------------------------------------------------------
Type modelType = model.GetType() ;
FieldInfo[] fields = modelType.GetFi elds();

for(int i = 0; i < fields.Length; i++)
{
Type fieldType = fields[i].FieldType;
object obj = fields[i].GetValue(model );
}
-----------------------------------------------------------------------------

Remember that I don't know ahead of time what types of collections I'll be
encountering. So though the 'fieldType' variable seems to correctly identify
the type of the collection, I can't figure out how to cast 'obj' to its true
type ... and then from there I could examine the elements that populate the
collection.

So I'm wondering two things:
1. Is what I'm asking to do possible?
2. Am I close or barking up the wrong tree?

--
Robert W.
Vancouver, BC
www.mwtech.com

Nov 17 '05 #1
2 2988
At their basic level a collection will implement IEnumerable and you'll be
able to iterate over the objects in the collection. As soon as you have an
object from that collection you can use reflection to ascertain it's real
type and extract methods and properties from it.

Get whatever object it is and see if it casts to IEnumerable. if it does,
it's a collection and you can use foreach(object o in blahblah) to get at
the items in it.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Robert W." <Ro*****@discus sions.microsoft .com> wrote in message
news:F1******** *************** ***********@mic rosoft.com...
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" [data model], 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 when I encounter
a
collection. Here's some starting code I've written:

-----------------------------------------------------------------------------
Type modelType = model.GetType() ;
FieldInfo[] fields = modelType.GetFi elds();

for(int i = 0; i < fields.Length; i++)
{
Type fieldType = fields[i].FieldType;
object obj = fields[i].GetValue(model );
}
-----------------------------------------------------------------------------

Remember that I don't know ahead of time what types of collections I'll be
encountering. So though the 'fieldType' variable seems to correctly
identify
the type of the collection, I can't figure out how to cast 'obj' to its
true
type ... and then from there I could examine the elements that populate
the
collection.

So I'm wondering two things:
1. Is what I'm asking to do possible?
2. Am I close or barking up the wrong tree?

--
Robert W.
Vancouver, BC
www.mwtech.com

Nov 17 '05 #2
Bob,

Maybe I'm just dense or perhaps I haven't had enough coffee ... but its the
casting to the desired type that I can't figure out.

For example, in my sample code, I need to figure out how to cast 'obj' to
the precise type that Reflection is saying it is. For argument's sake, let's
say that 'obj' is actually a custom collection (built from CollectionBase) .
Let's say it type name is "ComplexCla ss".

If it were a basic type, such as 'string' then I would do a cast like this:

string str = obj as string;

OR:

string str = (string) obj;
BUT I can't do this with my situation because I have only a reference to
'ComplexClass', not {ComplexClass} itself. Do you see the difference?

Your suggestion about using a foreach loop and making each element an object
doesn't appear to work.

Where am I going wrong?

Robert

"Bob Powell [MVP]" wrote:
At their basic level a collection will implement IEnumerable and you'll be
able to iterate over the objects in the collection. As soon as you have an
object from that collection you can use reflection to ascertain it's real
type and extract methods and properties from it.

Get whatever object it is and see if it casts to IEnumerable. if it does,
it's a collection and you can use foreach(object o in blahblah) to get at
the items in it.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Robert W." <Ro*****@discus sions.microsoft .com> wrote in message
news:F1******** *************** ***********@mic rosoft.com...
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" [data model], 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 when I encounter
a
collection. Here's some starting code I've written:

-----------------------------------------------------------------------------
Type modelType = model.GetType() ;
FieldInfo[] fields = modelType.GetFi elds();

for(int i = 0; i < fields.Length; i++)
{
Type fieldType = fields[i].FieldType;
object obj = fields[i].GetValue(model );
}
-----------------------------------------------------------------------------

Remember that I don't know ahead of time what types of collections I'll be
encountering. So though the 'fieldType' variable seems to correctly
identify
the type of the collection, I can't figure out how to cast 'obj' to its
true
type ... and then from there I could examine the elements that populate
the
collection.

So I'm wondering two things:
1. Is what I'm asking to do possible?
2. Am I close or barking up the wrong tree?

--
Robert W.
Vancouver, BC
www.mwtech.com


Nov 17 '05 #3

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

Similar topics

0
1730
by: Jason Coyne Gaijin42 | last post by:
I have seen several people looking for a way to access the Columns collection when using the AutoGenerate = true option. Some people have gotten so far as to find the private autoGenColumnsArray that has the information, but we as developers have no way to access this information. I have come up with a solution for the problem, (as I am sure many others have) using reflection. Here is some sample code that will print out the auto...
2
864
by: Jason Coyne Gaijin42 | last post by:
I have seen several people looking for a way to access the Columns collection when using the AutoGenerate = true option. Some people have gotten so far as to find the private autoGenColumnsArray that has the information, but we as developers have no way to access this information. I have come up with a solution for the problem, (as I am sure many others have) using reflection. Here is some sample code that will print out the auto...
8
1591
by: Rachel Suddeth | last post by:
I'm trying to use reflection to create an object at runtime where the type is given by a string. I thought we should be able to do that, but so far it's not working. I'm trying to work on reproducing the scenario in a simpler way, but it's slow going, and maybe there is something very basic I don't know yet.... Given the following lines of code: ------------- CredLookup testLU = new CredLookup(); string sLUType =...
1
24199
by: Mudassar | last post by:
i want to get the property value using reflection. Scenerio: i have a status bar on MDI form. it has property named "Panels" and i want to get a specific panel from that panels collection using reflection. Please let me know. Thanks C# Developer
1
2240
by: Edward Wilde | last post by:
Hi, Does anyone know how to examine items in the ASP.NET cache that are added using the OutputCache directive in framework 1.1 i.e. <%@ OutputCache Duration="300" VaryByParam="None" VaryByCustom="cmscontrol,cmsrole"%>
5
5386
by: Eric Goforth | last post by:
Hello, I have a generic subroutine that I pass an object and fieldname as arguments. The subroutine then uses reflection to search for the value of the fieldname. For example: 'Calling the Sub GetObjectValue(objMyCustomer, "Address.Zip")
2
7779
by: Jeff | last post by:
I am trying to dynamically load an assembly via reflection and then invoke a method of that assembly that will populate a custom type collection passed into the method byref. I am able to dynamically load both the DALC component (for the method call) and the Entity component (for the custom type collection to pass in), but I keep getting an error ( Message "Object type cannot be converted to target type.") when invoking the method. If I...
2
3811
by: Ryan | last post by:
Hi all, I've been banging my head on this for two days so I'd appreciate any pointers from the knowledgable amongst you. I have a win app that recurses through a path looking for assemblies to load, it then attempts to load each file in turn and examine its properties for a 'marker' property that defines it as a licencable class. The amount of errors/misinformation on this subject is staggering, every time I try a new approach I get...
2
1062
by: shapper | last post by:
Hello, I have the following method: public static IEnumerable GetRoles(CultureInfo culture, bool open) { switch (culture.TwoLetterISOLanguageName.ToLower()) { case "en": return new { new { Name = Role.Administrator, Description =
0
9926
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11095
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10812
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
10399
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7108
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
5780
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...
1
4597
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3223
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.