Solved

c# Getting Hashtable instance from PropertyInfo or FieldInfo

Posted on 2014-12-14
12
305 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
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
LVL 30

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 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

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VB.net/VSTO Excel Add-in 2 35
Build a string of emails from a gridview 2 27
EF5 How do I stop pre-compiled views? 8 46
Example code 13 34
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

740 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