?
Solved

c# Getting Hashtable instance from PropertyInfo or FieldInfo

Posted on 2014-12-14
12
Medium Priority
?
332 Views
Last Modified: 2014-12-15
I am iterating through an object structure looking at values using propertyInfo and FieldInfo.
If the type is a Hashtable I want to cast to the instance and print out the key/value pairs.
I am using the following code but it does not work.

Does anyone know if this is possible
private static PropertyInfo[] GetProperties(object obj)
        {
            return obj.GetType().GetProperties();
        }

        private static FieldInfo[] GetFields(object obj)
        {
            return obj.GetType().GetFields();
        }

private void AddDataItem(ListView listView, List<String> data)
        {
            if (data.Count > 0)
            {
                ListViewItem temp = new ListViewItem(data[0]);
                for (int i = 1; i < data.Count; i++)
                {
                    temp.SubItems.Add(data[i]);
                }
                listView.Items.Add(temp);
            }
        }

private void TV_Main_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode selected = TV_Main.SelectedNode;
            if (selected != null)
            {
                LV_MainProperties.Items.Clear();
                if (selected.Tag != null)
                {
                    Object obj = selected.Tag;
                   var properties = GetProperties(obj);

                    foreach (var p in properties)
                    {
                        try
                        {
                            if (p.PropertyType == typeof(Hashtable))
                            {
                                object propVal = p.GetValue(p, null);
                                Hashtable h = (Hashtable)propVal;
                                foreach (DictionaryEntry entry in h)
                                {
                                    AddDataItem(LV_MainProperties, new List<String> { entry.Key.ToString(), entry.Value.ToString() });
                                }
                            }
                            else
                            {
                                string name = p.Name;
                                var value = p.GetValue(obj, null);
                                AddDataItem(LV_MainProperties, new List<String> { name, value.ToString() });
                            }
                        }
                        catch
                        {

                        }
                    }

                    var fields = GetFields(obj);

                    foreach (var f in fields)
                    {
                        try
                        {
                            if (f.FieldType == typeof(Hashtable))
                            {
                                object propVal = f.GetValue(f);
                                Hashtable h = (Hashtable)propVal;
                                foreach (DictionaryEntry entry in h)
                                {
                                    AddDataItem(LV_MainProperties, new List<String> { entry.Key.ToString(), entry.Value.ToString() });
                                }
                            }
                            else
                            {
                                string name = f.Name;
                                var value = f.GetValue(obj);
                                AddDataItem(LV_MainProperties, new List<String> { name, value.ToString() });
                            }
                        
                        }
                        catch
                        {

                        }
                    }
                }
            }  

        }

Open in new window

0
Comment
Question by:jetbet
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
12 Comments
 

Author Comment

by:jetbet
ID: 40499484
Update:

If I use
if (p.ReflectedType == typeof(Hashtable))
    {
     object propVal = p.ReflectedType;  
.....

Open in new window

Then I do find the Type but propVal is the Hashtable class not the instance.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40499521
On the first glance I'd say:

if (p.ReflectedType == typeof(Hashtable))
    {
            Hashtable ht = (Hashtable)p;
             //do whatever you need with this hashtable...

Open in new window

0
 

Author Comment

by:jetbet
ID: 40499531
I would have thought that too, but I get an error 'Cannot convert type 'System.Reflection.PropertyInfo' to 'System.Collections.Hashtable'

Same thing for FieldInfo
0
Major Serverless Shift

Comparison of major players like AWS, Microsoft Azure, IBM Bluemix, and Google Cloud Platform

 
LVL 30

Accepted Solution

by:
anarki_jimbel earned 2000 total points
ID: 40499547
OK, I tried on my computer. Check my example. I believe you need to use "p.FieldType " but not "p.ReflectedType".

        private void button3_Click(object sender, EventArgs e)
        {
            Hashtable htab = new Hashtable();
            htab.Add(1, "a");
            htab.Add(2, "b");
            myTestClass mtc = new myTestClass();
            mtc.hasht = htab;

            FieldInfo[] props = mtc.GetType().GetFields();

            foreach (var p in props)
            {
                if (p.FieldType == typeof(Hashtable))
                {
                    //object propVal = p.ReflectedType;
                    Hashtable ht = (Hashtable)p.GetValue(mtc );
                }
            }




        }

Open in new window



You also need change  'object propVal = p.GetValue(p, null);' to
object propVal = p.GetValue(obj, null); in your code.
0
 

Author Comment

by:jetbet
ID: 40501186
No luck for me so far.
Even though the Hashtable is a field
public class RunnerDetail
    {
...
Hashtable       _winTable = new Hashtable();
...
public Hashtable winTable
        {
            get { return _winTable; }
            set { _winTable = value; }
        }
...

Open in new window


The code only triggers as a property

PropertyInfo[] props = obj.GetType().GetProperties();

                    foreach (var p in props)
                    {
                        try
                        {
                            if (p.PropertyType == typeof(Hashtable))
                            {
                                String message = "bob";

                            }
                            else if (p.ReflectedType  == typeof(Hashtable))
                            {
                                Hashtable ht = (Hashtable)p.GetValue(obj);
                                foreach (DictionaryEntry entry in ht)
                                {
                                    AddDataItem(LV_MainProperties, new List<String> { entry.Key.ToString(), entry.Value.ToString() });
                                }
                            }
                            else
                            {
                                string name = p.Name;
                                var value = p.GetValue(obj);
                                AddDataItem(LV_MainProperties, new List<String> { name, value.ToString() });
                            }
                        }
                        catch (Exception ex)
                        {
                            String message = ex.Message;
                        }
                    }

Open in new window


The test of p.PropetyType fails as it returns a collection not a Hashtable.
The test p.ReflectedType does return a Hashtable but then the cast
 Hashtable ht = (Hashtable)p.GetValue(obj);

Open in new window


fails with a parameter count mismatch
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40501242
What type of object is "obj" in your code? Is it hashtable?

PropertyInfo[] props =[b] obj.[/b]GetType().GetProperties();

Open in new window

0
 

Author Comment

by:jetbet
ID: 40501264
TreeNode selected = TV_Main.SelectedNode;
            if (selected != null)
            {
                LV_MainProperties.Items.Clear();
                if (selected.Tag != null)
                {
                    Object obj = selected.Tag;

Open in new window


So it is an instance of the class (RunnerDetail) I created.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40501299
The problem is  - I cannot understand the relation between your  'obj' and the hashtable. The 'tag' property has a type of 'Object'! So the code

Object obj = selected.Tag;

tells me nothing.

What is the relation between Tag and hashtable in this case?
0
 

Author Comment

by:jetbet
ID: 40501314
The Tag holds a reference to the instance of the object that the hashtable is part of.
The code lists all the names and values of the properties and fields on the object.
This works fine and will list that there is a hashtable there.
What I am trying to do is to drill down into the hashtable to show the values of the entries.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40501373
OK, I give up.
I showed you on my example how to retrieve the hashtable which is a property of the object. But I can't help without knowing details.

You tell
The test p.ReflectedType does return a Hashtable but then the cast
but
ReflectedType in your case should be your Tag object, not it's property.
I'd recommend to read MSDN documentation.

http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.reflectedtype(v=vs.110).aspx
0
 

Author Comment

by:jetbet
ID: 40501428
OK
Sorry if I have muddied the waters for you. I am unsure what details I was missing.
Thanks for all your help, I appreciate your efforts.
0
 

Author Closing Comment

by:jetbet
ID: 40501519
This was the correct solution. The following questions we not correct as I was passing an incorrect object into the Tag property.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question