Using Reflection

Reflection gives you the ability to inspect the code of a .NET application and execute that code dynamically. Various tools, such as VS 2012 Web Services and unit testing use reflection to perform actions based on the code you’ve written. When building a Web Service, VS 2012 uses reflection to inspect the attributes applied to classes and then read the method names, parameters, and return types of those methods to build an XML contract for clients to consume.The Unit Test runner uses reflection to find classes that contain tests and execute the methods decorated with test attributes.

Getting Type and TypeInfo

The first step in using reflection is to obtain a Type type or a TypeInfo type. A type is a class, struct, interface, or delegate that you write in order to inspect and learn more about the type. TheType andTypeInfo types let you furtherdelve into the internals of a type, using reflection, to learn about the membersof a type. The Type type has been part of .NET since v1.0. Microsoft introduced the TypInfo type in .NET v4.5, which also supports Windows 8
applications. The difference between Type and TypeInfo in .NET 4.5 is that Type provides reference support and TypeInfo is intended for execution.

If you already have an instance of an object, you can get its Type through the System.Object’s GetType method, like this:

In this example, the code has an instance of Program, prog, making it possible to call GetType to obtain the Type object. TheType object has manymethods for inspecting the type and it contains assembly information. This example prints the Name property, which is Program

Another way to obtain a Type is via the typeof operator. This is a C# operatorfrom basic C# syntax, but now you understand its true purpose and how to use it. Here’s an example:

You give the name of the type to the typeof operator and it returns a Type instance for that type. This example uses the AssemblyQualifiedName, whichgives the fully qualified name of the assembly, as follows:

With a Type, you can get a TypeInfo. Here’s an example:

The example above shows that you must first have a Type, which is testType in this case. With that Type , you can call GetTypeInfo to obtain a TypeInfo .


JoeMayoThis post is an excerpt from the online courseware for our C# 2012: Attributes, Reflections and Dynamic
course written by expert Joe Mayo.

Joe Mayo is an author, independent consultant, and instructor specializing in Microsoft .NET and Windows 8 technology. He has several years of software development experience and has worked with .NET since July 2000.

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *