Excerpt by Joe Mayo
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:
var prog = new Program(); Type progType = prog.GetType(); Console.WriteLine( "Program Type is: " + progType.Name);
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:
Type testType = typeof(TestAttribute); Console.WriteLine( "Fully Qualified Assembly Name: " + testType.AssemblyQualifiedName);
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:
Fully Qualified Assembly Name: Decorating_with_AttributeUsageAttribute.TestAttribute, Decorating with AttributeUsageAttribute, Version=18.104.22.168, Culture=neutral, PublicKeyToken=null
With a Type, you can get a TypeInfo. Here's an example:
Type testType = typeof(TestAttribute); TypeInfo testTypeInfo = testType.GetTypeInfo();
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 .
This course excerpt was originally posted August 13, 2013 from the online courseware C# 2012, Part 2 of 4: Attributes, Reflections, and Dynamic by Joe Mayo