SlideShare a Scribd company logo
.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

PPT
.NET Reflection
PPTX
Reflection in C#
PPT
Reflection in C Sharp
PPTX
Constructor & destructor based question- cbse cs class 12th
PPT
Smoke and Mirrors - Reflection in C#
PDF
Constructor & destructor
PPTX
C# Constructors
PPT
vb.net Constructor and destructor
.NET Reflection
Reflection in C#
Reflection in C Sharp
Constructor & destructor based question- cbse cs class 12th
Smoke and Mirrors - Reflection in C#
Constructor & destructor
C# Constructors
vb.net Constructor and destructor

What's hot (19)

PPT
Constructor
PPT
Generic
PPT
Design Patterns By Sisimon Soman
PDF
Object Oriented Programming with C#
PDF
Annotations Processor Tools (APT)
KEY
Building a Mongo DSL in Scala at Hot Potato
PPTX
Constructors
PDF
Objective-C talk
PPTX
PPTX
Pi j2.3 objects
PDF
Class vs struct for Swift
PDF
Introduction [1] - Software Testing Techniques (CIS640)
PPTX
Constructor and Destructor
PPTX
Design pattern (Abstract Factory & Singleton)
PPTX
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
PPT
Singleton design pattern
PPT
constructor and destructor-object oriented programming
PPTX
Constructor in java
PPTX
constructor and destructor
Constructor
Generic
Design Patterns By Sisimon Soman
Object Oriented Programming with C#
Annotations Processor Tools (APT)
Building a Mongo DSL in Scala at Hot Potato
Constructors
Objective-C talk
Pi j2.3 objects
Class vs struct for Swift
Introduction [1] - Software Testing Techniques (CIS640)
Constructor and Destructor
Design pattern (Abstract Factory & Singleton)
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Singleton design pattern
constructor and destructor-object oriented programming
Constructor in java
constructor and destructor
Ad

Viewers also liked (16)

PDF
IIE Solution - Maximizing IE Value-1
DOC
chandan yadav Resume
PPS
ROOF LEAKING SOLUTIONSs
PDF
VCG Training 9/21/16
PDF
Reflection Mcq's by Zubair Dar
ODP
Algoritmo
PDF
Research Techniques Workshop
PPTX
Pabrik Furniture Stainless Steel Surabaya & Sidoarjo
DOCX
Trabajo lengua 3 trimeste
PPTX
Tecnología Educativa
PPTX
VCG Information Session
ODP
Arreglos de gustavo
PDF
Integritet og talentprogram førte til tops
PPTX
ปัญหาการฆ่าตัวตาย
PPTX
Defense thesis
IIE Solution - Maximizing IE Value-1
chandan yadav Resume
ROOF LEAKING SOLUTIONSs
VCG Training 9/21/16
Reflection Mcq's by Zubair Dar
Algoritmo
Research Techniques Workshop
Pabrik Furniture Stainless Steel Surabaya & Sidoarjo
Trabajo lengua 3 trimeste
Tecnología Educativa
VCG Information Session
Arreglos de gustavo
Integritet og talentprogram førte til tops
ปัญหาการฆ่าตัวตาย
Defense thesis
Ad

Similar to Reflection Slides by Zubair Dar (20)

PPT
Design Patterns
PPT
NNUG Certification Presentation
PPTX
.NET Attributes and Reflection - What a Developer Needs to Know...
PPT
01-introduction OOPS concepts in C++ JAVA
PPT
01-introductionto Object ooriented Programming in JAVA CS.ppt
PPTX
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
PDF
Object-oriented Analysis, Design & Programming
PPTX
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
PPT
Advanced c#
PPTX
TypeScript . the JavaScript developer best friend!
PPTX
15reflection in c#
PPTX
Graph Databases in the Microsoft Ecosystem
PPTX
Introduction to Design Patterns in Javascript
PPTX
L04 base patterns
PPTX
Better Understanding OOP using C#
PPTX
SQL Saturday 28 - .NET Fundamentals
PPT
Object Oriented Programming In .Net
PPT
CSharp_03_ClassesStructs_and_introduction
PPTX
Object-oriented programming
Design Patterns
NNUG Certification Presentation
.NET Attributes and Reflection - What a Developer Needs to Know...
01-introduction OOPS concepts in C++ JAVA
01-introductionto Object ooriented Programming in JAVA CS.ppt
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
Object-oriented Analysis, Design & Programming
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Advanced c#
TypeScript . the JavaScript developer best friend!
15reflection in c#
Graph Databases in the Microsoft Ecosystem
Introduction to Design Patterns in Javascript
L04 base patterns
Better Understanding OOP using C#
SQL Saturday 28 - .NET Fundamentals
Object Oriented Programming In .Net
CSharp_03_ClassesStructs_and_introduction
Object-oriented programming

Recently uploaded (20)

PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
master seminar digital applications in india
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Cell Structure & Organelles in detailed.
PPTX
Pharma ospi slides which help in ospi learning
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Institutional Correction lecture only . . .
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
master seminar digital applications in india
VCE English Exam - Section C Student Revision Booklet
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
A systematic review of self-coping strategies used by university students to ...
Cell Structure & Organelles in detailed.
Pharma ospi slides which help in ospi learning
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Final Presentation General Medicine 03-08-2024.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Institutional Correction lecture only . . .
human mycosis Human fungal infections are called human mycosis..pptx
Microbial diseases, their pathogenesis and prophylaxis
STATICS OF THE RIGID BODIES Hibbelers.pdf

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
  • 16. References • Microsoft • http://www.codersource.net/csharp_tutorial_reflection.html • http://www.csharp-examples.net/reflection-examples/

Editor's Notes

  • #6: .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.
  • #8: 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
  • #14: 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.
  • #15: 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.
  • #16: 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.