How to explore a given type dynamically

In this blog I will show you how to explore a given type properties, methods, fields and so forth programmatically. To do so, create a new windows application then add a label, a textbox, a button and a list box into it so that it appears like below:


 
Figure 1               

Then add this code within the button1 event handler scope:

private void button1_Click(object sender, EventArgs e)

{

 

try

{

   

    Person myPerson = new Person("Bejaoui", "Bechir");

    Type myType = Type.GetType(textBox1.Text);

    MemberInfo[] r = myType.GetMembers();

    MessageBox.Show("The total number of members is : " + r.Length);

    int index = 1;

    foreach (MemberInfo x in r)

    {

        listBox1.Items.Add("Member" + index.ToString() + " : " + x.Name + " is " +  x.MemberType);

       

index++;

    }

}

catch (NullReferenceException caught)

{ MessageBox.Show("This is not a type",caught.Message); }

}

}

Run the application and put a given type within the textbox, say, System.DateTime for example, by the way a full name type is required to achieve the goal, otherwise, a null reference exception will be risen. Now, try to observe what happens.

Good Dotneting!!!

Next Recommended Reading Data Types & Type Conversions in C#