Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting collection of all members of a class

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();
like image 441
Sanchaita Chakraborty Avatar asked Jul 21 '11 09:07

Sanchaita Chakraborty


3 Answers

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.

like image 185
dknaack Avatar answered Oct 29 '22 01:10

dknaack


From msdn, members of a class include:

Fields

Constants (comes under Fields)

Properties

Methods

Events

Operators

Indexers (comes under Properties)

Constructors

Destructors

Nested Types

When you do GetMembers on a class you get all of these (including static ones defined on the class like static/const/operator, not to mention the instance ones) of that class and the instance members of the classes it inherited (no static/const/operator of base classes) but wouldn't duplicate the overridden methods/properties.

To filter out, you have GetFields, GetProperties, GetMethods, and for greater flexibility, there is FindMembers

like image 21
nawfal Avatar answered Oct 29 '22 00:10

nawfal


Well, it depends a little on what you get. For example:

   static void Main(string[] args)
    {
        Testme t = new Testme();
        Type obj = t.GetType();

        MemberInfo[] objMember = obj.GetMembers();

       foreach (MemberInfo m in objMember)
       {
           Console.WriteLine(m);
       } 
    }


    class Testme
    {
        public String name;
        public String phone;
    }

Returns

System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
Void .ctor()
System.String name
System.String phone

Which is what I expected, remember, just because your class inherits from somewhere, there are other things provided by default.

like image 37
BugFinder Avatar answered Oct 28 '22 23:10

BugFinder