Solved

c# Getting Hashtable instance from PropertyInfo or FieldInfo

Posted on 2014-12-14
12
268 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
  • 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 29

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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 500 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 29

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 29

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 29

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Code works but it's slow 28 70
application restarter  - for an exe that hangs 9 25
C# Desktop Application 3 29
Send SMS from VB via Sierra Wireless Modem 2 21
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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…

786 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