Reflection Is the ability to of instpecting an assemblies metadata at run time. It is used to find all types in an assembly and/or dynamically invoke methods in an assembly
2. Overview
• Reflection core concepts
• Exploring metadata
• Detail information
• Attributes
• Building Types at runtime
3. What is reflection?
Is the ability to of instpecting an assemblies metadata at run time. It is used to
find all types in an assembly and/or dynamically invoke methods in an
assembly
Use Of Reflection
1. When you drag and drop a button on a win forms or an asp.net application.
The properties windows use the reflection to show all the properties of the
button class. So reflection is extensively use by IDE or UI designers
2. Late binding can be achieved by using Reflection
Information can be:
• Data of the class
• Names of the methods
• Constructors of that object
4. Why reflection
• explore assembly metadata
• creating objects dynamically
• invoking methods dynamically
• write “generic” code that works with
different types
• implement sophisticated programming
techniques
5. Reflection Core Concepts
Metadata
Single location for type information and code
Code is literally contained within type information
Every .NET object can be queried for its type
Type metadata can be explored with Reflection
Dynamic Type System
Highly dynamic and language independent
Types may be extended and built at run time
Allows on-the-fly creation of assemblies
.NET Compilers use .NET to emit .NET code
6. • Accessing meta-data: System.Object.GetType()
– All .NET classes (implicitly) inherit System.Object
– Available on every .NET class; simple types too
• Explicit language support for type meta-data
– C#, JScript.NET: typeof(…)
– VB.NET: If TypeOf … Is … Then …
• Determining Type Identity
– Types have unique identity across any assembly
– Types can be compared for identity
• if ( a.GetType() == b.GetType() ) { … };
7. ReflectionReflection
System.TypeSystem.Type
• Provides access to metadata for any .NET type
• Returned by System.Object.GetType()
• Allows drilling down into all facets of a type
– Category: Simple, Enum, Struct or Class
– Methods and Constructors, Parameters and Return
– Fields and Properties, Arguments and Attributes
– Events, Delegates, and Namespaces
7
8. ExampleExample
public class customer
{ public int id { get; set; }
public string name { get; set; }
public customer()
{
id = -1;
name = string.Empty;
}
public customer(int id, string name)
{this.id = id;
this.name = name;
}
public void printid()
{ Console.WriteLine("id is {0}",this.id);}
public void printname()
{Console.WriteLine("Name is {0}",this.name);}
}
class Program
{
static void Main(string[] args)
{
}
}
9. Type t =
Type.GetType("csharp.customer");//static method
on type clss
customer c = new customer();
Console.WriteLine("Full Name {0}",
t.FullName);
Console.WriteLine(" Name {0}", t.Name);
Console.WriteLine("Namespace {0}",
t.Namespace);
Console.WriteLine();
In main class
10. Type t = Type.GetType("csharp.customer");
Console.WriteLine("Full Name {0}", t.FullName);
Console.WriteLine(" Name {0}", t.Name);
Console.WriteLine("Namespace {0}",
t.Namespace);
Console.WriteLine();
In main class( Get
Propeties)
11. Console.WriteLine("Methods in customers");
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo method in methods)
{
Console.WriteLine(method.ReturnType
+ " " + method.Name);
}
Console.WriteLine();
In main class(Get Methods)
12. In main class(Get Constructor)
Console.WriteLine("constructor in customers");
ConstructorInfo[] constructors = t.GetConstructors();
foreach (ConstructorInfo constructor in constructors)
{
Console.WriteLine(constructor.ToString());
//Console.WriteLine(constructor.Name);//it dsnt give any info
}
14. Reflection The Bigger Picture
• Types know their module; modules know their types
• Modules know their assembly and vice versa
• Code can browse and search its entire context
14
Assembly
Module Module Module
Class Struct
Constructor
Method
Method
Field
Class
Interface
Class
Delegate
Class
Interface
Interface
15. Summary
• Reflection = System.Type + GetType()
• Explore Type Information at Runtime
• Enables Attribute-Driven Programming
• Use Emit Classes to Produce .NET Assemblies
• Bottom Line: Fully Self-Contained Structural Model
.NET reflection and its core concepts build on the experience of the COM type library model. Applications are able to evaluate the type information at runtime and invoke services in a late bound fashion. The two core elements that enable this are "metadata" and .NET's dynamic common type system.
Metadata
Metadata provides a single location for the type information and code. In .NET assemblies of the entire structural information about application is bundled together with a description of its runtime behavior, expressed in the Microsoft intermediate language. The structural information describes the overall shape of assemblies and modules into detail each data type and class. Class methods and all other active entities are stored with their call signature and return value types and their MSIL code. MSIL is therefore really part of the description of any method, because the actual code that is executed at runtime is a compiled representation of the MSIL in native machine code.
While the COM type library information is restricted to those types for which inclusion in the library was explicitly requested, metadata is available and accessible for each and every type that is being used in .NET managed code. Every .NET types, from simple scalar types such as a plain integer to complex classes can be queried for its type. At runtime, data types are represented by special .NET runtime class, System.Type. This class allows close inspection of every aspect of a runtime data type. The framework's ability to make type information available at runtime through this class is what is called "reflection".
Dynamic Type System
The universal exploration of type information is enabled by the dynamic common type system (CTS). All languages that target the .NET framework share the CTS. The language compilers automatically create the type information stored in the metadata, which can later be read by applications written in any other language. Because the underlying type system is now independent of the implementation language used, the restricted type model that we know from COM no longer applies and the exchangeable type information is equivalent to the type information used to build applications. Under the hood, the type information exposed through reflection is sometimes even richer than what can be expressed using the intrinsic language elements of languages like C#.
The "Emit" part of reflection, which is covered in the second part of this module allows types the extended (by inheritance) or be entirely build at runtime. This allows for the on the fly creation of new assemblies and modules and in fact .NET compilers use .NET to emit .NET code.
Access to meta-data for any .NET type
Every instance of System.Type is a dynamically created wrapper around the metadata of certain class. When you invoke “GetType()” on an object, the runtime will gather the requested metadata, stuff it into a fresh System.Type instance and hand it to you.
Returned by System.Object.GetType()
Instances of the System.Type class are most prominently returned by the System.Object.GetType() method as this has been shown previously, but as you descend into the depths of the .NET framework you will find that Type objects are used quite often throughout the lower-levels of the Framework hierarchy.
Allows drilling down into all facets of a type
The System.Type class will allow you to explore all facets of a type like the type “category”, a class’ or structure’s methods, constructors and their parameters and return values. Furthermore, of course, all other aspects of such types like properties, fields, events and delegates and, of course, the namespace the class is located in can be explored.
Summary: Everything you may ever want to know
Custom attributes are the killer-app for Reflection!
Custom attributes are the real killer application for Reflection and something that you should really consider looking at very closely.
The Reflection features that we highlighted up to here, like all the detailed member information are certainly useful for implementing late-bound applications and for creating more solid code, but attributes indeed enable a whole new development paradigm: attribute-driven programming.
Attributes enable declarative behavior
Attributes are special elements (classes) in the .NET Framework that allow you to augment any structural element of .NET classes and structures with auxiliary information that is not immediately part of the class’s runtime behavior but serves to provide additional information that is either being evaluated by the runtime and the .NET Framework or your own frameworks.
An example for this is the [serializable] attribute, which tells the Serialization framework that it is allowed to serialize a class’s state as-is and using the class metadata for Remoting or persistent storage. If the attribute is not present, the class implementer essentially denies that permission and either provides an own implementation for serialization through the ISerializable interface or does not p ermit serialization and remote marshaling at all.
Types know their Module, Modules know their types
Another strong point of the metadata is that it allows navigating the entire context of a type. A module, reflected by the System.Reflection.Module class, knows all of the types it defines and implements and each types knows its implementing module.
Modules know their Assembly and vice versa
Likewise, all modules know and make their container assembly accessible and the assembly can list all modules it contains.
Code can browse and search its entire context
Finally, the Application Domain (AppDomain) class of the “current” application knows all loaded assemblies, so that you have a full information model about an application’s metadata at any time and from wherever you need it.
Reflection = System.Type + GetType()
At the heart of Reflection are the method GetType() that is available on each and every object in .NET and the System.Type class that it returns. If you could only remember a single thing about Reflection, this should be it.
Explore Type Information for everything at Runtime
The System.Type class and the additional classes in the System.Reflection namespace that accessible through it let you explore every structural element of .Net applications at runtime without extra effort at development or compile time.
Enables Attribute-driven programming
Reflection also enables the powerful Attribute-driven programming model that lets you add declarative behavior to code.
Use Emit Classes to Produce .NET Assemblies
You can use the System.Reflection.Emit namespace classes to create .NET Assemblies in much the same way as the .NET toolsets do it.
Bottom line: Fully Self-Contained Structural Model
To sum it all up: With Reflection, .NET provides and contains an entirely self-describing and self-contained structural model that does not require any external tools to create .NET compliant components.