Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following method to return a dictionary with all public attributes of an object. I can get the name of the attributes (class variables) but I can not get the values ​​of the same. Could anyone tell me how to achieve this in the method below:

XML
public Dictionary<String, String> ObjectProperty(object objeto)
 {
    Dictionary<String, String> dictionary = new Dictionary<String, String>();

    Type type = objeto.GetType();
    FieldInfo[] field = type.GetFields();
    PropertyInfo[] myPropertyInfo = type.GetProperties();

    String value = null;

    foreach (var propertyInfo in myPropertyInfo)
    {
        value = (string) propertyInfo.GetValue(this, null); //Here is the error
        dictionary.Add(propertyInfo.Name.ToString(), value);

    }

    return dictionary;

}
Posted
Comments
Thomas Daniels 17-Aug-13 11:11am    
Which error do you get?
Sergey Alexandrovich Kryukov 17-Aug-13 12:33pm    
In .NET, "attributes" mean .NET attributes, not properties. What exactly do you mean by "attributes"?

By the way, many properties are classified as "attributes" in UML, but .NET terminology is different.

—SA

1 solution

Use this in the row you have marked:
C#
value = propertyInfo.GetValue(objeto).ToString(); 

But you have to know, that this is a really simplified approach. Since properties can be more complex than scalar values if you want to make your method more general, you will have to add more logic.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900