Solved

c# Getting Hashtable instance from PropertyInfo or FieldInfo

Posted on 2014-12-14
12
244 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
What type of object is "obj" in your code? Is it hashtable?

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

Open in new window

0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:jetbet
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

772 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now