Overview of reflection

Reflection in C# means inspecting the contents of an assembly at run time. It returns the metadata for each class present in the assembly—so, it returns the following:

  • The name of the class
  • All of the properties present in the class
  • All of the methods along with their return types and function parameters
  • All of the attributes present in the class

In Chapter 10Find, Execute, and Create Types at Runtime Using Reflection, we will do a deep dive on reflection; however, in this chapter, we will just go through a code sample of how we can implement reflection in C# to decode all of the metadata present in the assembly.

To use reflection, we need to include the System.Reflection namespace, which helps us to use required classes such as Assembly. Please refer to the following function, which reads a particular assembly based on its path and reads all of the classes, methods, and parameters present in the assembly:

static private void ReadAssembly()
{
string path = @"C:UCN Code BaseProgramming-in-C-Exam-70-483-
MCSD-GuideBook70483SamplesChapter8inDebugABC.dll";
Assembly assembly = Assembly.LoadFile(path);
Type[] types = assembly.GetTypes();
foreach(var type in types)
{
Console.WriteLine("Class : " + type.Name);
MethodInfo[] methods = type.GetMethods();
foreach(var method in methods)
{
Console.WriteLine("--Method: " + method.Name);
ParameterInfo[] parameters = method.GetParameters();
foreach (var param in parameters)
{
Console.WriteLine("--- Parameter: " + param.Name + " :
" + param.ParameterType);
}
}
}
Console.ReadLine();
}

In the preceding code base, we have declared a fully qualified path for an assembly in C#. Next, we have declared an object of the Assembly class and have retrieved an array of all Types present in the assembly. Then, we are looping through each type and finding out the methods in each of those types. Once we have a list of methods for each of the types, we retrieve the list of parameters present in that method and their parameter types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.50.222