Introduction to Reflection API
Type and TypeInfo
Type class represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.
The .NET 4.5 Framework includes some changes to the typical reflection use cases. Most importantly, the Type object has been split into two separate classes: Type and TypeInfo. A TypeInfo instance contains the definition for a Type, and a Type now contains only reference data. If you're using reflection from within a .NET 4.5 Desktop or Web application, the old API is still available alongside the new API methods.
Lets say we have class:
public class Student { public string FullName { get; set; } public int Class { get; set; } public DateTime DateOfBirth { get; set; } public string GetCharacteristics() { return ""; } }
And we want to get all methods and properties declared within this type. Using TypeInfo we can do this in easy and clean way:
TypeInfo studentInfo = typeof(Student).GetTypeInfo(); IEnumerable<PropertyInfo> declaredProperties = studentInfo.DeclaredProperties; IEnumerable<MethodInfo> declaredMethods = studentInfo.DeclaredMethods;
Also we can get it`s name and namespase using properties Name & Namespace
Type student = typeof(Student); string name = student.Name; string ns = student.Namespace;
Also it is possible to get type of any existing object using Object.GetType method
Type type = myObject.GetType();
BindingFlags Enumeration
When you will search members and types you may need to use BindingFlags. BindingFlags specifies flags that control binding and the way in which the search for members and types is conducted by reflection.
This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.
More detailed description you can read on MSDN
Examples
Get all types within assembly and output it`s names and properties count
using System; using System.Collections.G...
Obtain Type information using Object.GetType method
using System; using System.Text; public...
Check if object is type
using System; using System.IO; public c...