Getting Information About Class Programatically (methods in class/properties of class)


Introduction

In this article I will show you how can we get the information related to some type/class using Type Class programatically like how many constructors are there in Class , which Data Members are there names of methods in the class etc .

Technology

CSharp .net 2.0/3.5

Implementation

Type Class Provides methods for getting information related to some type like, 

Constructors in Class
Method Names of Class
Properties of Class

For this sample we will create one class like below and try to get all those information like constuctors in class, methods in class and properties related to that class

Type.GetConstructor() method returns Array of ConstructorInfo
Type.GetMethods() method returns Array of MethodInfo
Type.GetProperties() method returns Array of PropertyInfo




For example below is our class1

class code
------------

 public class Class1

    {

        int Var1;

        int Var2; 

        public Class1()

        {

            throw new System.NotImplementedException();

        } 

        public int GetSetVar1

        {

            get

            {

                return Var1;

            }

            set

            {

                Var1 = value;

            }

        } 

        public int GetSetVar2

        {

            get

            {

                return Var2;

            }

            set

            {

                Var2 = value;

            }

        } 

        public void Method1()

        { 

        } 

        public void Method2()

        { 

        }

    }


And here is Form code to access information related to the Class1 defined above

private void button1_Click(object sender, EventArgs e)

{

    //find Out Which Methods Are there In Class1 Programatically

    Type mytype = typeof(Class1);

    MethodInfo[] methodsInClass = mytype.GetMethods();

 

    listBox1.Items.Clear();

    foreach (MethodInfo minfo in methodsInClass)

    {

        listBox1.Items.Add(minfo.Name);

    }

 

    //Find Which Constructors are there in Class1

 

    ConstructorInfo[] constructorInfo = mytype.GetConstructors();

    listBox2.Items.Clear();

    foreach (ConstructorInfo cinfo in constructorInfo)

    {

        listBox2.Items.Add(cinfo.Name);

    }

 

    //Find Which Datamembers Are there in Class1

    PropertyInfo[] pInfo = mytype.GetProperties();

    listBox3.Items.Clear();

    foreach (PropertyInfo pinfo in pInfo)

    {

        listBox3.Items.Add(pinfo.Name);

    }

}


Conclusion

We have just seen in this article about how to get information about class programatically.


Similar Articles