Chapter 12. Reflection

Reflection is the mechanism provided by the .NET Framework to allow you to inspect how a program is constructed. Using reflection, you can obtain information such as the name of an assembly and what other assemblies a given assembly imports. You can even dynamically call methods on a type in a given assembly. Reflection also allows you to create code dynamically and compile it to an in-memory assembly or to build a symbol table of type entries in an assembly. Reflection is a very powerful feature of the framework, and, as such, is guarded by the runtime, requiring the ReflectionPermission be granted to assemblies doing this type of work. “Code Access Security” has only two permission sets that give all reflection access by default: FullTrust and Everything. The LocalIntranet permission set allows for the ReflectionEmit privilege that allows for emitting metadata and creating assemblies, but not the TypeInformation privilege for inspecting other assemblies or the MemberAccess privilege for performing dynamic invocation of methods on types in assemblies. In this chapter, you will see how you can use reflection to dynamically invoke members on types, figure out all of the assemblies a given assembly is dependent on, and inspect assemblies for different types of information. Reflection is a great way to understand how things are put together in .NET; this chapter provides a starting point.

12.1. Listing Imported Assemblies

Problem

You need to determine ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.