Getting collection of all members of a class

Sanchaita Chakraborty picture Sanchaita Chakraborty · Jul 21, 2011 · Viewed 29.5k times · Source

I want to get the collection of all the members that are present in a class. How do I do that? I am using the following, but it is giving me many extra names along with the members.

Type obj  =  objContactField.GetType();
MemberInfo[] objMember = obj.GetMembers();
String name = objMember[5].Name.ToString();

Answer

dknaack picture dknaack · Jul 21, 2011

Get a collection of all the properties of a class and their values:

class Test
{
    public string Name { get; set; }
}

Test instance = new Test();
Type type = typeof(Test);

Dictionary<string, object> properties = new Dictionary<string, object>();
foreach (PropertyInfo prop in type.GetProperties())
    properties.Add(prop.Name, prop.GetValue(instance));

Note that you will need to add using System.Collections.Generic; and using System.Reflection; for the example to work.