Sunday, August 12, 2007

Reflection > Usage and Emit

REFLECTION
• Reflection provides objects (of type Type) that encapsulates assemblies, modules or types
• Type (Type is the name of a class), is the root of the System.Reflection functionality and primary way to access metadata
• Reflection can be used to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object
• Reflection also allows accessing Attributes
• Example of GetType method, this method is inherited by all types from the Object base class

int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

• Example that uses Reflection to obtain full name of a loaded assembly:

System.Reflection.Assembly o = System.Reflection.Assembly.Load(mscorlib.dll);
System.Console.WriteLine( o.GetName() );

USAGE SCENARIOS OF REFLECTION
• When accessing attributes in program’s metadata
• For accessing and instantiating types in an assembly
• For building new types at runtime, using classes in System.Reflection.Emit
• For performing late binding, accessing methods on types created at runtime

REFLECTION.EMIT
• The System.Reflection.Emit namespace contains classes that allow a compiler or a tool to emit metadata and MSIL and optionally generate a PE file on disk

No comments: