This session is based on the previous session - Part 53 Reflection in C#. Please watch part 53, before continuing with this session.
In this session we will develop a simple winforms application. Please design the form as shown in the image below.
In this session we will develop a simple winforms application. Please design the form as shown in the image below.
Part 54 - C# Tutorial - Reflection Example
In the properties window
Set the Name of the text box to txtTypeName
Set the Name of the button to btnDiscoverTypeInformation
Set the Name of the list boxes, to lstMethods, lstProperties, and lstConstructors
Now double click the button control to generate the event handler.
Copy and paste the following code in the button click event handler (btnDiscoverTypeInformation_Click).
string TypeName = txtTypeName.Text;
Type T = Type.GetType(TypeName);
lstMethods.Items.Clear();
lstProperties.Items.Clear();
lstConstructors.Items.Clear();
MethodInfo[] methods = T.GetMethods();
foreach (MethodInfo method in methods)
{
lstMethods.Items.Add(method.ReturnType.Name + " " + method.Name);
}
PropertyInfo[] properties = T.GetProperties();
foreach (PropertyInfo property in properties)
{
lstProperties.Items.Add(property.PropertyType.Name + " " + property.Name);
}
ConstructorInfo[] constructors = T.GetConstructors();
foreach (ConstructorInfo constructor in constructors)
{
lstConstructors.Items.Add(constructor.ToString());
}
Run the application and enter the type name for which you want to find type information. For example, if you enter System.Console, you should see the list of methods, properties and constructors.
hi
ReplyDeleteCan I use Reflection to do the introspection of an external class to my project?
Scenario: I put many files in a folder. How can I use those classes, using Reflection? How can I upload without knowing their name? Know only the folder where they were saved (note: the file implement a specific interface, this is important to me)
Hi Venkat,
ReplyDeletei am getting a Null Exception when i write System.Data.Common.DbCommand in the txtTypeName
Can you tell me the reason
i have also tried
Type T = Type.GetType(System.Data.Common.DbCommand);
Can you tell me Why is that?
Try this
ReplyDeletestring TypeName=txtTypeName.Text.ToString()
string TypeName = txtTypeName.Text.ToString();
DeleteType T = Type.GetType(TypeName);
if (T == null)
{
lstMethod.Items.Add("Null Value");
}
else
{
MethodInfo[] methods = T.GetMethods();
foreach (MethodInfo method in methods)
{
lstMethod.Items.Add(method.Name);
}
}
Still it returns Null
string TypeName = txtTypeName.Text;
ReplyDeleteType T = Type.GetType(TypeName);
T is still returning Null
string TypeName = txtTypeName.Text;
ReplyDeleteType T = Type.GetType(TypeName);
T is still returning Null
I am getting this Still NullReference Exception.What to do ?Can soe one Help.