SlideShare a Scribd company logo
1 of 16
.Net Reflection
Nabell (BCSF12M060)
Sheraz Manzoor (BCSF13M009)
Arham Butt (BCSF13M025)
Farhan (BCSF13M058)
Zubair Dar (BCSF13M065)
Overview
• Reflection core concepts
• Exploring metadata
• Detail information
• Attributes
• Building Types at runtime
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
Why reflection
• explore assembly metadata
• creating objects dynamically
• invoking methods dynamically
• write “generic” code that works with
different types
• implement sophisticated programming
techniques
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
• 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() ) { … };
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
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)
{
}
}
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
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)
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)
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
}
Reflection
Attributes
• Custom attributes are the killer-app
for Reflection!
• Attributes enable declarative behavior
• Attributes allow data augmentation
13
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
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
References
• Microsoft
• http://www.codersource.net/csharp_tutorial_reflection.html
• http://www.csharp-examples.net/reflection-examples/

More Related Content

What's hot

Design Patterns By Sisimon Soman
Design Patterns By Sisimon SomanDesign Patterns By Sisimon Soman
Design Patterns By Sisimon Soman
Sisimon Soman
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
11prasoon
 

What's hot (19)

Constructor
ConstructorConstructor
Constructor
 
Generic
GenericGeneric
Generic
 
Design Patterns By Sisimon Soman
Design Patterns By Sisimon SomanDesign Patterns By Sisimon Soman
Design Patterns By Sisimon Soman
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
Annotations Processor Tools (APT)
Annotations Processor Tools (APT)Annotations Processor Tools (APT)
Annotations Processor Tools (APT)
 
Building a Mongo DSL in Scala at Hot Potato
Building a Mongo DSL in Scala at Hot PotatoBuilding a Mongo DSL in Scala at Hot Potato
Building a Mongo DSL in Scala at Hot Potato
 
Constructors
ConstructorsConstructors
Constructors
 
Objective-C talk
Objective-C talkObjective-C talk
Objective-C talk
 
Generics C#
Generics C#Generics C#
Generics C#
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Class vs struct for Swift
Class vs struct for SwiftClass vs struct for Swift
Class vs struct for Swift
 
Introduction [1] - Software Testing Techniques (CIS640)
Introduction [1] - Software Testing Techniques (CIS640)Introduction [1] - Software Testing Techniques (CIS640)
Introduction [1] - Software Testing Techniques (CIS640)
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructor
 

Viewers also liked

IIE Solution - Maximizing IE Value-1
IIE Solution - Maximizing IE Value-1IIE Solution - Maximizing IE Value-1
IIE Solution - Maximizing IE Value-1
Stanley Rusiniak
 
chandan yadav Resume
chandan yadav Resumechandan yadav Resume
chandan yadav Resume
Chandan Yadav
 

Viewers also liked (16)

IIE Solution - Maximizing IE Value-1
IIE Solution - Maximizing IE Value-1IIE Solution - Maximizing IE Value-1
IIE Solution - Maximizing IE Value-1
 
chandan yadav Resume
chandan yadav Resumechandan yadav Resume
chandan yadav Resume
 
ROOF LEAKING SOLUTIONSs
ROOF LEAKING SOLUTIONSsROOF LEAKING SOLUTIONSs
ROOF LEAKING SOLUTIONSs
 
Teatro barroco
Teatro barrocoTeatro barroco
Teatro barroco
 
VCG Training 9/21/16
VCG Training 9/21/16VCG Training 9/21/16
VCG Training 9/21/16
 
Reflection Mcq's by Zubair Dar
Reflection Mcq's by Zubair DarReflection Mcq's by Zubair Dar
Reflection Mcq's by Zubair Dar
 
Algoritmo
AlgoritmoAlgoritmo
Algoritmo
 
Research Techniques Workshop
Research Techniques WorkshopResearch Techniques Workshop
Research Techniques Workshop
 
Pabrik Furniture Stainless Steel Surabaya & Sidoarjo
Pabrik Furniture Stainless Steel Surabaya & SidoarjoPabrik Furniture Stainless Steel Surabaya & Sidoarjo
Pabrik Furniture Stainless Steel Surabaya & Sidoarjo
 
Trabajo lengua 3 trimeste
Trabajo lengua 3 trimesteTrabajo lengua 3 trimeste
Trabajo lengua 3 trimeste
 
Tecnología Educativa
Tecnología EducativaTecnología Educativa
Tecnología Educativa
 
VCG Information Session
VCG Information SessionVCG Information Session
VCG Information Session
 
Arreglos de gustavo
Arreglos de gustavoArreglos de gustavo
Arreglos de gustavo
 
Integritet og talentprogram førte til tops
Integritet og talentprogram førte til topsIntegritet og talentprogram førte til tops
Integritet og talentprogram førte til tops
 
ปัญหาการฆ่าตัวตาย
ปัญหาการฆ่าตัวตายปัญหาการฆ่าตัวตาย
ปัญหาการฆ่าตัวตาย
 
Defense thesis
Defense thesisDefense thesis
Defense thesis
 

Similar to Reflection Slides by Zubair Dar

NNUG Certification Presentation
NNUG Certification PresentationNNUG Certification Presentation
NNUG Certification Presentation
Niall Merrigan
 
Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & Programming
Allan Mangune
 

Similar to Reflection Slides by Zubair Dar (20)

C#ppt
C#pptC#ppt
C#ppt
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
NNUG Certification Presentation
NNUG Certification PresentationNNUG Certification Presentation
NNUG Certification Presentation
 
.NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know....NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know...
 
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don GriffinSenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
 
Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & Programming
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
15reflection in c#
15reflection  in c#15reflection  in c#
15reflection in c#
 
Graph Databases in the Microsoft Ecosystem
Graph Databases in the Microsoft EcosystemGraph Databases in the Microsoft Ecosystem
Graph Databases in the Microsoft Ecosystem
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
L04 base patterns
L04 base patternsL04 base patterns
L04 base patterns
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
 
SQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET FundamentalsSQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET Fundamentals
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Angular
AngularAngular
Angular
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Recently uploaded (20)

Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 

Reflection Slides by Zubair Dar

  • 1. .Net Reflection Nabell (BCSF12M060) Sheraz Manzoor (BCSF13M009) Arham Butt (BCSF13M025) Farhan (BCSF13M058) Zubair Dar (BCSF13M065)
  • 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 }
  • 13. Reflection Attributes • Custom attributes are the killer-app for Reflection! • Attributes enable declarative behavior • Attributes allow data augmentation 13
  • 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

Editor's Notes

  1. .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.
  2. 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
  3. 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.
  4. 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.
  5. 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.