C# and .NET interview questions: - What is reflection?

 Posted by ArticlesMaint on 9/20/2011 | Category: .NET Framework Interview questions | Views: 19082


Reflection helps us to browse methods, properties and function of a given class or assembly on run time. You can also invoke the methods and functions using reflection. Below is a simple sample code where we are browsing in run time through methods and function of “MyClass”.

MyClass objMyClass = new MyClass();

// Get the class type
Type parameterType = objMyClass.GetType();
string name = parameterType.Name;
// Browse through members
foreach (MemberInfo objMemberInfo in parameterType.GetMembers())
{
Console.WriteLine(objMemberInfo.Name);

}
// Browse through properties.
foreach (PropertyInfo objPropertyInfo in parameterType.GetProperties())
{
Console.WriteLine(objPropertyInfo.Name);

}

If you want to invoke method and function you need to use the invoke member function as shown in the below code.

parameterType.InvokeMember("Display",BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Instance,null, objMyClass, null);

Also see the following video on use of "VAR" keyword in .NET and C#: -



Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Akiii on: 9/21/2011
Microsoft's .NET stores type information as Metadata. Reflection is a mechanism to access this Metadata information and enable us to access it with our .NET Code.

Source:- MSDN

Thanks and Regards
Akiii

Login to post response