professional documents
home
Profile
docsters
request
Blogs
Upload
about me
contact me
user photo
sanyam chaudhary
I am a software enginner and would like to add Computer Scientist in my "About Me" some day.
submit clear
The .NET Framework is designed as an integrated environment for seamlessly developing and running applications on the Internet, on the desktop as Windows Forms, and even on mobile devices (with the Compact Framework). Its primary objectives are as follows:     To provide a consistent object-oriented environment across the range of applications. To provide an environment that minimizes the versioning conflicts ("DLL Hell") that has bedeviled Windows (COM) programmers, and to simplify the code distribution/installation process. To provide a portable environment, based on certified standards that can be hosted by any operating system. Already, C# and a major part of the .NET runtime, the Common Language Infrastructure (CLI), have been standardized by the ECMA.[1] To provide a managed environment in which code is easily verified for safe execution The CLR—which is Microsoft's implementation of the CLI standard—handles code execution and all of the tasks associated with it: compilation, memory management, security, thread management, and enforcement of type safety and use. Code that runs under the CLR is referred to as managed code. This is to distinguish it from unmanaged code that does not implement the requirements to run in the CLR—such as COM or Windows API based components. The other major component, the Framework Class Library, is a reusable code library of types (classes, structures, and so on) available to applications running under .NET. Common Intermediate Language (CIL) The CLI defines a platform-independent virtual code execution environment. It specifies no operating system, so it could just as easily be Linux as Windows Architecture defined by CLI specifications Briefly, the CLI defines two implementations: a minimal implementation known as a Kernel Profile and a more feature rich Compact Profile. The kernel contains the types and classes required by a compiler that is CLI compliant. The Base Class Library holds the basic data type classes, as well as classes that provide simple file access, define security attributes, and implement one-dimensional arrays. The Compact Profile adds three class libraries: an XML library that defines simple XML parsing, a Network library that provides HTTP support and access to ports, and a Reflection library that supports reflection (a way for a program to examine itself through metacode). Common Language Runtime The Common Language Runtime manages the entire life cycle of an application: it locates code, compiles it, loads associated classes, manages its execution, and ensures automatic memory management. Moreover, it supports cross-language integration to permit code generated by different languages to interact seamlessly. Compiling .NET Code Compilers that are compliant with the CLR generate code that is targeted for the runtime, as opposed to a specific CPU. This code, known variously as Common Intermediate Language (CIL), Intermediate Language (IL), or Microsoft Intermediate Language (MSIL), is an assembler-type language that is packaged in an EXE or DLL file. Note that these are not standard executable files and require that the runtime's Just-in-Time (JIT) compiler convert the IL in them to a machine-specific code when an application actually runs. Because the Common Language Runtime is responsible for managing this IL, the code is known as managed code. the Common Language Runtime neither knows—nor needs to know—which language an application is created in. Its interaction is with the language-independent IL. Because applications communicate through their IL, output from one compiler can be integrated with code produced by a different compiler. Common Language Runtime functions Another .NET goal, platform portability, is addressed by localizing the creation of machine code in the JIT compiler. This means that IL produced on one platform can be run on any other platform that has its own framework and a JIT compiler that emits its own machine code. In addition to producing IL, compilers that target the CLR must emit metadata into every code module. The metadata is a set of tables that allows each code module to be selfdescriptive. The tables contain information about the assembly containing the code, as well as a full description of the code itself. This information includes what types are available, the name of each type, type members, the scope or visibility of the type, and any other type features. Metadata has many uses:    The most important use is by the JIT compiler, which gathers all the type information it needs for compiling directly from the metacode. Metadata is used in the Garbage Collection process (memory management). The garbage collector (GC) uses metadata to know when fields within an object refer to other objects so that the GC can determine what objects can and can't have their memory reclaimed. .NET provides a set of classes that provide the functionality to read metadata from within a program. This functionality is known collectively as reflection. It is a powerful feature that permits a program to query the code at runtime and make decisions based on its discovery. Common Type System The CTS provides a base set of data types for each language that runs on the .NET platform. In addition, it specifies how to declare and create custom types, and how to manage the lifetime of instances of these types. Two things stand out in this figure. The most obvious is that types are categorized as reference or value types. This taxonomy is based on how the types are stored and accessed in memory: reference types are accessed in a special memory area (called a heap) via pointers, whereas value types are referenced directly in a program stack. Assemblies All of the managed code that runs in .NET must be contained in an assembly. Logically, the assembly is referenced as one EXE or DLL file. Physically, it may consist of a collection of one or more files that contain code or resources such as images or XML data.An assembly is created when a .NET compatible compiler converts a file containing source code into a DLL or EXE file.An assembly contains a manifest, metadata, and the compiler-generated Intermediate Language (IL). Let's take a closer look at these: Manifest. Each assembly must have one file that contains a manifest. The manifest is a set of tables containing metadata that lists the names of all files in the assembly, references to external assemblies, and information such as name and version that identify the assembly. Metadata In addition to the manifest tables just described, the C# compiler produces definition and reference tables. The definition tables provide a complete description of the types contained in the IL. For instance, there are tables defining types, methods, fields, parameters, and properties. The reference tables contain information on all references to types and other assemblies. The JIT compiler relies on these tables to convert the IL to native machine code. Single file assembly The assembly is more than just a logical way to package executable code. It forms the very heart of the .NET model for code deployment, version control, and security:    All managed code, whether it is a stand-alone program, a control, or a DLL library containing reusable types, is packaged in an assembly. In .NET jargon, an assembly forms a version boundary. The version field in the manifest applies to all types and resources in the assembly. Thus, all the files comprising the assembly are treated as a single unit with the same version. An assembly also forms a security boundary on which access permissions are based. C# uses access modifiers to control how types and type members in an assembly can be accessed. Two of these use the assembly as a boundary: public permits unrestricted access from any assembly; internal restricts access to types and members within the assembly. Private and Shared Assemblies Assemblies may be deployed in two ways: privately or globally. Assemblies that are located in an application's base directory or a subdirectory are called privately deployed assemblies. The installation and updating of a private assembly could not be simpler. It only requires copying the assembly into the directory, called the AppBase, where the application is located. No registry settings are needed. A shared assembly is one installed in a global location, called the Global Assembly Cache (GAC), where it is accessible by multiple applications. The most significant feature of the GAC is that it permits multiple versions of an assembly to execute side-byside. To support this, .NET overcomes the name conflict problem that plagues DLLs by using four attributes to identify an assembly: the file name, a culture identity, a version number, and a public key token. Core Note: An assembly that is signed with a public/private key is referred to as a strongly named assembly. All shared assemblies must have a strong name Code Verification As part of the JIT compile process, the Common Language Runtime performs two types of verification: IL verification and metadata validation. The purpose is to ensure that the code is verifiably type-safe. Framework Class Library The Framework Class Library (FCL) is a collection of classes and other types (enumerations, structures, and interfaces) that are available to managed code written in any language that targets the CLR. This is significant, because it means that libraries are no longer tied to specific compilers. The FCL comprises hundreds of assemblies (DLLs), and each assembly may contain multiple namespaces. In addition, a namespace may span multiple assemblies. To demonstrate, let's look inside an FCL assembly C:\>Ildasm /adv Namespaces provide a roadmap for navigating the FCL. For example, if your applications are Web based, you'll spend most of your time exploring the types in the System.Web.* namespaces. System.Reflection Contains types that permit the runtime inspection of metadata. The Emit namespace allows a compiler or tool to System.Reflection.Emit generate metadata and IL dynamically. Understanding the C# Compiler /target (/t) Specifies the type of output file created: /t:exe builds a *.exe console application. This is the default output. /t:library builds a *.dll assembly. /t:module builds a module (Portable Executable file) that does not contain a manifest. /t:winexe builds a *.exe Windows Forms assembly. Test Your Understanding 2: What is managed code? What is unmanaged code? Managed code is produced by a compiler that meets the Common Type System (CTS) requirements that are necessary before code produced by it can be run by the Common Language Runtime (CLR). Unmanaged code does not meet the CTS standard. The Windows API and COM objects are examples of unmanaged code 3: What is the difference between the Common Type System and the Common Language Specification? The Common Type System defines the types and their members that must be used by compilers that create code to run on the Common Language Runtime. The Common Language Specification provides stricter requirements that ensure interoperability between languages 5: What is the role of the Global Assembly Cache? The Global Assembly Cache (GAC) holds shared assemblies—assemblies that can be used by more than one application. Assemblies in the GAC have a digital signature that uniquely identifies them, even if they have the same file name 7: What is the relationship between a namespace and an assembly? A namespace usually identifies a group of types that provide related services. An assembly may contain one or more namespaces. Also, a namespace may contain types in more than one assembly. Access Modifiers Public A class can be accessed from any assembly. Protected Applies only to a nested class (class defined within another class). Access is limited to the container class or classes derived from the container class. Internal Access is limited to classes in the same assembly. This is the default access. private Applies only to a nested class. Access is limited to the container class. protected internal The only case where multiple modifiers may be used. Internal Access is limited to the current assembly or types derived from the containing class. abstract Indicates that a class is to be used only as a base class for other classes. This means that you cannot create an instance of the class directly. Any class derived from it must implement all of its abstract methods and accessors. Despite its name, an abstract class can possess nonabstract methods and properties. sealed static Specifies that a class cannot be inherited (used as a base class). Note that .NET does not permit a class to be both abstract and sealed. Specifies that a class contains only static members (.NET 2.0). Methods Methods are to classes as verbs are to sentences. They perform the actions that define the behavior of the class. A method is identified by its signature, which consists of the method name and the number and data type of each parameter. A signature is considered unique as long as no other method has the same name and matching parameter list. In addition to parameters, a method has a return type—void if nothing is returned—and a modifier list that determines its accessibility and polymorphic behavior. Method Modifiers Modifier static Description The method is part of the class's state rather than any instances of the class. This means that it can be referenced directly by specifying classname.method (parameters) without creating an instance of the class. Designates that the method can be overridden in a subclass. This cannot be used with static or private access modifiers. class. This enables the method to define behavior unique to the subclass. The overriden method in the base class must be virtual. virtual override Specifies that the method overrides a method of the same name in a base new Permits a method in an inherited class to "hide" a non-virtual method with a same name in the base class. It replaces the original method rather than overriding it. Prevents a derived class from overriding this method.   sealed Is used in a derived class that will serve as the base for its own subclasses. Must be used with the override modifier. abstract The method contains no implementation details and must be implemented by any subclass. Can only be used as a member of an abstract class. extern Indicates that the method is implemented externally. It is generally used with the DLLImport attribute that specifies a DLL to provide the implementation. Static Modifier: As with other class members, the static modifier defines a member whose behavior is global to the class and not specific to an instance of a class. The modifier is most commonly used with constructors (described in the next section) and methods in helper classes that can be used without instantiation. using System; class Conversions { // class contains functions to provide metric conversions private static double cmPerInch = 2.54; private static double gmPerPound = 455; public static double inchesToMetric(double inches) { return(inches * cmPerInch); } public static double poundsToGrams(double pounds) { return(pounds * gmPerPound); } } class Test { static void Main() { double cm, grams; cm = Conversions.inchesToMetric(28.5); grams = Conversions.poundsToGrams(984.4); } } In this example, the Conversions class contains methods that convert units from the English to metric system. There is no real reason to create an instance of the class, because the methods are invariant (the formulas never change) and can be conveniently accessed using the syntax classname.method(parameter). Method Inheritance with Virtual and Override Modifiers Inheritance enables a program to create a new class that takes the form and functionality of an existing (base) class. The new class then adds code to distinguish its behavior from that of its base class. The capability of the subclass and base class to respond differently to the same message is classical polymorphism. In practical terms, this most often means that a base and derived class(es) provide different code for methods having the same signature. By default, methods in the base class cannot be changed in the derived class. To overcome this, .NET provides the virtual modifier as a cue to the compiler that a method can be redefined in any class that inherits it. Similarly, the compiler requires that any derived class that alters a virtual method preface the method with the override modifier. Figure 3-2 and Listing 3-6 provide a simple illustration of this. Virtual Methods using System; class Fiber { public } class Natural:Fiber {public override string ShowMe() { return("Natural");} } class Cotton:Natural { } class Test { static void Main () { Fiber fib1 = new Natural(); Fiber fib2 = new Cotton(); string fibVal; fibVal = fib1.ShowMe(); // Returns "Natural" // Instance of Natural // Instance of Cotton public override string ShowMe() { return("Cotton");} virtual string ShowMe() { return("Base");} fibVal = fib2.ShowMe(); } } // Returns "Cotton" Figure 3-2. Relationship between base class and subclasses for Listing 3-6 In this example, Cotton is a subclass of Natural, which is itself a subclass of Fiber. Each subclass implements its own overriding code for the virtual method ShowMe. fib1.ShowMe(); fib2.ShowMe(); //returns //returns "Natural" "Cotton" A subclass can inherit a virtual method without overriding it. If the Cotton class does not override ShowMe(), it uses the method defined in its base class Natural. In that case, the call to fib2.ShowMe() would return "Natural". New Modifier and Versioning There are situations where it is useful to hide inherited members of a base class. For example, your class may contain a method with the same signature as one in its base class. To notify the compiler that your subclass is creating its own version of the method, it should use the new modifier in the declaration. ShowMe() is no longer virtual and cannot be overridden. For Natural to create its own version, it must use the new modifier in the method declaration to hide the inherited version. Observe the following:    An instance of the Natural class that calls ShowMe()invokes the new method: Natural myFiber = new Natural();   string fibTtype = myFiber.ShowMe(); // returns "Natural"       Cotton inherits the new method from Natural: Cotton myFiber = new Cotton(); string fibType = myFiber.ShowMe(); // returns "Natural" If ShowMe were declared as private rather than public in Natural, Cotton would inherit ShowMe from Fiber, because it cannot inherit a method that is out of scope. Using the New Modifier for Versioning public class Fiber { public string ShowMe() {return("Base");} public virtual string GetID() {return("BaseID");} } public class Natural:Fiber { // Hide Inherited version of ShowMe new public string ShowMe() {return("Natural");} public override string GetID() {return("NaturalID");} } public class Cotton:Natural { } // Inherits two methods: ShowMe() and GetID() Sealed and Abstract Modifiers A sealed modifier indicates that a method cannot be overridden in an inheriting class; an abstract modifier requires that the inheriting class implement it. In the latter case, the base class provides the method declaration but no implementation. This code sample illustrates how an inheriting class uses the sealed modifier to prevent a method from being overridden further down the inheritance chain. Note that sealed is always paired with the override modifier. class A { public virtual void PrintID{....} } class B: A { sealed override public void PrintID{...} } class C:B { // This is illegal because it is sealed in B. override public void PrintID{...} } An abstract method represents a function with a signature—but no implementation code—that must be defined by any non-abstract class inheriting it. This differs from a virtual method, which has implementation code, but may be redefined by an inheriting class. The following rules govern the use abstract methods:   Abstract methods can only be declared in abstract classes; however, abstract classes may have non-abstract methods. The method body consists of a semicolon: public abstract void myMethod();   Although implicitly virtual, abstract methods cannot have the virtual modifier. A virtual method can be overridden by an abstract method. When facing the decision of whether to create an abstract class, a developer should also consider using an interface. The two are similar in that both create a blueprint for methods and properties without providing the implementation details. There are differences between the two, and a developer needs to be aware of these in order to make the better choice. The section on interfaces in this chapter offers a critical comparison. Constructors FAQs 1. Is the constructor mandatory for a class? Yes, it is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier. Say, for example, we have only private constructor(s) in the class and if we are interested in instantiating the class, i.e., want to create an object of the class, then having only private constructor will not be sufficient and in fact it will raise an error. So, proper access modifies should be provided to the constructors. 2. What if I do not write the constructor? In such case, the compiler will try to supply the no parameter constructor for your class, behind the scene. Compiler will attempt this only if you do not write the constructor for the class. If you provide any constructor (with or without parameters), then compiler will not make any such attempt. 3. What if I have the constructor public myDerivedClass(), but not the public myBaseClass()? It will raise an error. If either the no parameter constructor is absent or it is inaccessible (say it is private), it will raise an error. You will have to take the precaution here. 4. Can we access static members from the non-static (normal) constructors? Yes, we can. There is no such restriction on non-static constructors. But there is one on static constructors that it can access only static members. Introduction Broadly speaking, a constructor is a method in the class which gets executed when its object is created. Usually, we put the initialization code in the constructor. Writing a constructor in the class is damn simple, have a look at the following sample: public class mySampleClass { public mySampleClass() { // This is the constructor method. } // rest of the class members goes here. } When the object of this class is instantiated, this constructor will be executed. Something like this: mySampleClass obj = new mySampleClass() // At this time the code in the constructor will // be executed Constructor Overloading C# supports overloading of constructors, that means, we can have constructors with different sets of parameters. So, our class can be like this: public class mySampleClass { public mySampleClass() { // This is the no parameter constructor method. // First Constructor } public mySampleClass(int Age) { // This is the constructor with one parameter. // Second Constructor } public mySampleClass(int Age, string Name) { // This is the constructor with two parameters. // Third Constructor } // rest of the class members goes here. } Well, note here that call to the constructor now depends on the way you instantiate the object. For example: mySampleClass obj = new mySampleClass() // At this time the code of no parameter // constructor (First Constructor)will be executed mySampleClass obj = new mySampleClass(12) // At this time the code of one parameter // constructor(Second Constructor)will be // executed. The call to the constructors is completely governed by the rules of overloading here. Calling Constructor from another Constructor You can always make a call to one constructor from within another. Say, for example: public class mySampleClass { public mySampleClass(): this(10) { // This is the no parameter constructor method. // First Constructor } public mySampleClass(int Age) { // This is the constructor with one parameter. // Second Constructor } } Very first of all, let us see what is this syntax: public mySampleClass(): this(10) Here, this refers to same class, so when we say this(10), we actually mean execute the public mySampleClass(int Age) method. The above way of calling the method is called initializer. We can have at the most one initializer in this way in the method. Another thing which we must know is the execution sequence i.e., which method will be executed when. Here, if I instantiate the object as: mySampleClass obj = new mySampleClass() Then the code of public mySampleClass(int Age) will be executed before the code of mySampleClass(). So, practically the definition of the method: public mySampleClass(): this(10) { // This is the no parameter constructor method. // First Constructor } is equivalent to: public mySampleClass() { mySampleClass(10) // This is the no parameter constructor method. // First Constructor } Note: Above (just above this line) code is mentioned there for pure analogy and will not compile. The intention here is to tell the flow of execution if initializers are used. We cannot make an explicit call to the constructors in C#, treating them as if any simple method, for example: statement mySampleClass(10) in the above code will not work. The only way you can call one constructor from another is through initializers. For the VB.NET programmers: you can make the call to another constructor of the same class by the syntax Me.New(param list), but it should be the first line of your calling constructor method. So ultimately, the code of the called constructor runs prior to the code of the calling constructor, which is same as initializers here. Note that only this and base (we will see it further) keywords are allowed in initializers, other method calls will raise an error. This is sometimes called Constructor chaining. Huff… Simple thing made tough, but this is how it is. Anyway, let us proceed further. Behavior of Constructors in Inheritance Let us first create the inherited class. public class myBaseClass { public myBaseClass() { // Code for First Base class Constructor } public myBaseClass(int Age) { // Code for Second Base class Constructor } // Other class members goes here } public class myDerivedClass : myBaseClass // Note that I am inheriting the class here. { public myDerivedClass() { // Code for the First myDerivedClass Constructor. } public myDerivedClass(int Age):base(Age) { // Code for the Second myDerivedClass Constructor. } // Other class members goes here } Now, what will be the execution sequence here: If I create the object of the derived class as: myDerivedClass obj = new myDerivedClass() Then the sequence of execution will be: 1. public myBaseClass() method. 2. and then public myDerivedClass() method. Note: If we do not provide initializer referring to the base class constructor then it executes the no parameter constructor of the base class. Note one thing here: we are not making any explicit call to the constructor of base class neither by initializer nor by the base keyword, but it is still executing. This is the normal behavior of the constructor. If I create an object of the derived class as: myDerivedClass obj = new myDerivedClass(15) Then the sequence of execution will be: 1. public myBaseClass(int Age) method 2. and then public myDerivedClass(int Age) method Here, the new keyword base has come into picture. This refers to the base class of the current class. So, here it refers to the myBaseClass. And base(10) refers to the call to myBaseClass(int Age) method. Also note the usage of Age variable in the syntax: public myDerivedClass(int Age):base(Age). [Understanding it is left to the reader]. Private Constructors Private constructors, the constructors with the "private" access modifier, are a bit special case. It is because we can neither create the object of the class, nor can we inherit the class with only private constructors. But yes, we can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining. Say for example, my class is something like this : public class myClass { private MyClass() { Console.WriteLine("This is no parameter Constructor"); } public MyClass(int var):this() { Console.WriteLine("This is one parameter Constructor"); } // Other class methods goes here } Then we can create the object of this class by the statement: MyClass obj = new MyClass(10); The above statement will work fine, but the statement MyClass obj = new MyClass(); will raise an error : 'Constructors.MyClass.MyClass()' is inaccessible due to its protection level It is possible to have the class with only the private constructors. But yes as I said, such class can neither be instantiated nor be inherited. If we try to inherit the class with only private constructors then we will get the same error as above. Also recall, once you provide constructor from your side the compiler will not add the no-parameter public constructor to your class. Well, one of the usage scenarios of such class could be – when you have only static members in the class and you don't need to instantiate it. Phew… lost… Anything left in constructors? Yes, Static Constructors. Ha!! Now, what are they? Let us see.. Static Constructors This is a new concept introduced in C#. By new here, I mean that it was not available for the C++ developers. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly. The syntax of writing the static constructors is also damn simple. Here it is: public class myClass { static myClass() { // Initialization code goes here. // Can only access static members here. } // Other class methods goes here } Notes for Static Constructors: 1. 2. 3. 4. There can be only one static constructor in the class. The static constructor should be without parameters. It can only access the static members of the class. There should be no access modifier in static constructor definition. Ok fine, all the above points are fine, but why is it like that? Let us go step by step here. Firstly, the call to the static method is made by the CLR and not by the object, so we do not need to have the access modifier to it. Secondly, it is going to be called by CLR, who can pass the parameters to it, if required. So we cannot have parameterized static constructor. Thirdly, non-static members in the class are specific to the object instance. So static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class. Fourthly, overloading needs the two methods to be different in terms of methods definition, which you cannot do with Static Constructors, so you can have at the most one static constructor in the class. Now, one question raises here, can we have two constructors as: public class myClass { static myClass() { // Initialization code goes here. // Can only access static members here. } public myClass() { // Code for the First myDerivedClass Constructor. } // Other class methods goes here } This is perfectly valid, though doesn't seem to be in accordance with overloading concepts. But why? Because the time of execution of the two methods are different. One is at the time of loading the assembly and one is at the time of object creation Introduction Reflection is a notable addition to the .NET Framework. Through Reflection, a program collects and manipulates its own metadata. It is a powerful mechanism to introspect the assemblies and objects at runtime. The Reflection APIs are contained in the System.Reflection namespace. Reflection allows the programmer to inspect and collect information about the type, properties, methods and events of an object and to invoke the methods of that object through the Invoke method. Reflection is a powerful tool to develop Reverse Engineering applications, class browsers and property editors. In this article, I will provide examples for the following uses of Reflection:   Collecting metadata of an assembly and discovering the types of classes in it. Dynamic invocation of methods and properties. Through late binding, the properties and methods of a dynamically instantiated object can be invoked based on type discovery.  Creating types at runtime using Reflection.Emit. This is the most usable feature of reflection. The user can create new types at runtime and use them to perform required tasks. Reflection to find out the assemblies used by a program using System; using System.Reflection ; namespace ReflectionDemoCSharp { class ReferencedAssemblies { [STAThread] static void Main(string[] args) { Assembly[] appAssemblies = System.AppDomain.CurrentDomain.GetAssemblies (); foreach (Assembly assembly in appAssemblies ) { Console.WriteLine (assembly.FullName ); } Console.ReadLine (); } } } Output mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ReflectionDemoCSharp, Version=1.0.1882.29904, Culture=neutral, PublicKeyToken=null The System.AppDomain class represents an application domain. AppDomain is an isolated environment where the application executes. Assembly[] appAssemblies = System.AppDomain.CurrentDomain.GetAssemblies (); The GetAssemblies() method returns the assemblies loaded by ReflectionDemoCSharp. It outputs mscorlib.dll and ReflectionDemoCSharp. Reflecting on an assembly and Discovering the existing types First of all, we load an assembly dynamically with the Assembly.Load() method. public static Assembly.Load(AssemblyName) We pass the MsCorLib.dll. Assembly LoadedAssembly = Assembly.Load("mscorlib.dll"); Once the assembly is loaded, we call the GetTypes() method to get an array of Type objects. System.Type[] ExistingTypes = LoadedAssembly.GetTypes (); The Type returned can represent the types of classes, interfaces, or enumerators. using System; using System.Reflection ; namespace ReflectionDemoCSharp { class ReflectedTypes { [STAThread] static void Main(string[] args) { Assembly LoadedAssembly = Assembly.Load ("mscorlib.dll"); System.Type[] ExistingTypes = LoadedAssembly.GetTypes (); foreach(Type type in ExistingTypes) Console.WriteLine (type.ToString ()); Console.WriteLine (ExistingTypes.Length + " Types Discovered in mscorlib.dll"); Console.ReadLine (); } } } Output (The actual output will fill several pages, so only few are shown.) System.Object System.ICloneable System.Collections.IEnumerable System.Collections.ICollection System.Collections.IList System.Array System.Array+SorterObjectArray System.Array+SorterGenericArray System.Collections.IEnumerator 1480 Types Discovered in mscorlib.dll Reflecting on a Single Type In our next example, we will reflect on a single type and find out its members. The Type.GetType(TypeName) method takes a string argument and returns the corresponding System.Type. We query the type using the Type.GetMembers() method to return an array of members in the type. using System; using System.Reflection ; namespace ReflectionDemoCSharp { class ReflectedTypes { [STAThread] static void Main(string[] args) { Type TypeToReflect = Type.GetType("System.Int32"); System.Reflection.MemberInfo[] Members =type.GetMembers(); Console.WriteLine ("Members of "+TypeToReflect.ToString ()); Console.WriteLine(); foreach (MemberInfo member in Members ) Console.WriteLine(member); Console.ReadLine (); } } } Here is the output: Members of System.Int32 Int32 MaxValue Int32 MinValue System.String ToString(System.IFormatProvider) System.TypeCode GetTypeCode() System.String ToString(System.String, System.IFormatProvider) Int32 CompareTo(System.Object) Int32 GetHashCode() Boolean Equals(System.Object) System.String ToString() System.String ToString(System.String) Int32 Parse(System.String) Int32 Parse(System.String, System.Globalization.NumberStyles) Int32 Parse(System.String, System.IFormatProvider) Int32 Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) System.Type GetType()       System.Reflection.MemberInfo[] Members =type.GetMembers() - returns all the members of the Type being queried. System.Reflection.MethodInfo[] Methods =Type.GetMethods() - returns only the methods in the Type being queried. System.Reflection.FieldInfo[] Fields =Type.GetFields() - returns only the fields in the Type being queried. System.Reflection.PropertyInfo[] Properties = type.GetProperties () - returns the properties in the Type being queried. System.Reflection.EventInfo[] Events = type.GetEvents() - returns the events in the Type being queried. System.Reflection.ConstructorInfo[] Constructors = type.GetConstructors () - returns the constructors in the Type being queried. System.Type[] Interfaces = type.GetInterfaces() - returns the interfaces in the Type being queried.  Dynamic Invocation with Type.InvokeMember() The next example demonstrates how to dynamically invoke a method using the method type.InvokeMember(). The ― Equals‖ method of System.String, which compares two strings for equality, is invoked using the InvokeMember() method. The program passes two string arguments for comparison. The type.InvokeMember() allows us to execute methods by name. Parameters of InvokeMember() method are: 1. The first parameter to InvokeMember() is the name of the member we want to invoke. It is passed as a string. 2. The second parameter is a member of the BindingFlags enumeration. BindingFlags enumeration specifies flags that control binding and the way in which to look for members and types. 3. The third parameter is a Binder object that defines a set of properties and enables binding. Or it can be null, in which case the default Binder will be used. The Binder parameter gives the user explicit control over how the reflection selects an overloaded method and converts arguments. 4. The fourth parameter is the object on which to invoke the specified member. 5. The fifth parameter is an array of arguments to pass to the member to invoke. using System; using System.Reflection ; namespace ReflectionDemoCSharp { class ReflectedTypes { [STAThread] static void Main(string[] args) { Type TypeToReflect = Type.GetType("System.String"); object result = null; object[] arguments = {"abc","xyz"}; result = TypeToReflect.InvokeMember ("Equals", BindingFlags.InvokeMethod, null, result, arguments); Console.WriteLine (result.ToString ()); Console.ReadLine (); } } } The output in this case is false. Reflection.Emit - Creating Types Dynamically at Runtime and Invoking their Methods Reflection.Emit supports dynamic creation of new types at runtime. You can create an assembly dynamically, and then you can define the modules, types and methods you want included in it. The assembly can run dynamically or can be saved to disk. The methods defined in the new assembly can be invoked using the Type.InvokeMember() method. Reflection.Emit also allows the compiler to emit its metadata and Microsoft Intermediate Language (MSIL) during runtime. Let us create a class DoMath and define a method DoSum in the assembly named Math. The first thing to do is to create an object of type AssemblyName and give it a name. AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "Math"; Next, we use the AssemblyBuilder class to define a dynamic assembly, in the Current Domain of the application. We have to pass two parameters AssemblyName and an enumeration value of AssemblyBuilderAccess (Run, RunAndSave or Save). The value of AssemblyBuilderAccess determines whether the assembly can be run only or it can be saved to the disk. AssemblyBuilder CreatedAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave ); Now, in our dynamically created assembly, we create an assembly Module. For this, use the created AsemblyBuilder object and call its DefineDynamicModule() method, which in turn returns a ModuleBuilder object. We pass the name of the Module and the filename in which it will be saved. ModuleBuilder AssemblyModule = CreatedAssembly.DefineDynamicModule("MathModule","Math.dll"); Our next step is to create a public class in this AssemblyModule. Let’s define a public class named ― DoMath‖. We use a TypeBuilder class to dynamically define a class. For this, we call the AssemblyModule.DefineType() method. The DefineType() returns a TypeBuilder object. TypeBuilder MathType = AssemblyModule.DefineType("DoMath", TypeAttributes.Public | TypeAttributes.Class); In the ―DoSum‖ class, we create a method ― Sum‖ which adds two integers and returns the result. The MethodBuilder class is used to define the method, its parameter types and the return type. We call the TypeBuilder object's DefineMethod() method and pass the name of the method, its attributes, return type, and an array of types of the parameters. System.Type [] ParamTypes = new Type[] { typeof(int),typeof(int) }; MethodBuilder SumMethod = MathType.DefineMethod("Sum", MethodAttributes.Public, typeof(int), ParamTypes); Next, we define the two parameters of the method ― Sum‖ using the ParameterBuilder class. We call the DefineParameter() method of the MethodBuilder object, passing the position, attribute of the parameter, and an optional name for the parameter. ParameterBuilder Param1 = SumMethod.DefineParameter(1,ParameterAttributes.In ,"num1"); ParameterBuilder Param2 = SumMethod.DefineParameter(2,ParameterAttributes.In ,"num2"); We then use the MethodBuilder object created earlier to get an ILGenerator object. ILGenerator ilGenerator = SumMethod.GetILGenerator(); It is the ILGenerator object that emits the opcode or Microsoft Intermediate Language (MSIL) instruction. These opcodes are the same opcodes generated by a C# compiler. The OpCodes class contains fields that represent MSIL instructions. We use these fields to emit the actual opcode. So we emit the opcode of the two arguments of the ― Sum‖ method. The opcodes are pushed into the stack. Then we specify the operation – in our case, add two numbers. Now the stack will contain the sum of the two arguments. The OpCodes.Ret will return the value in the stack. ilGenerator.Emit(OpCodes.Ldarg_1); ilGenerator.Emit (OpCodes.Ldarg_2); ilGenerator.Emit (OpCodes.Add ); ilGenerator.Emit(OpCodes.Ret); Now we create the class and return the assembly. MathType.CreateType(); return CreatedAssembly; Here is the example code: Collapse using System; using System.Reflection; using System.Reflection.Emit; namespace ConsoleApplication1 { public class ReflectionEmitDemo { public Assembly CreateAssembly() { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "Math"; AssemblyBuilder CreatedAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave ); ModuleBuilder AssemblyModule = CreatedAssembly.DefineDynamicModule("MathModule","Math.dll"); TypeBuilder MathType = AssemblyModule.DefineType("DoMath", TypeAttributes.Public | TypeAttributes.Class); System.Type [] ParamTypes = new Type[] { typeof(int),typeof(int) }; MethodBuilder SumMethod = MathType.DefineMethod("Sum", MethodAttributes.Public, typeof(int), ParamTypes); ParameterBuilder Param1 = SumMethod.DefineParameter(1,ParameterAttributes.In, "num1"); ParameterBuilder Param2 = SumMethod.DefineParameter(2,ParameterAttributes.In, "num2"); ILGenerator ilGenerator = SumMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_1); ilGenerator.Emit (OpCodes.Ldarg_2); ilGenerator.Emit (OpCodes.Add ); ilGenerator.Emit(OpCodes.Ret); MathType.CreateType(); return CreatedAssembly; } } } Our next aim is to invoke the ― Sum‖ method of the dynamically created Type. Let us create an object of the ReflectionEmitDemo class and call its CreateAssembly method to return the dynamically created assembly. Then we reflect on the EmitAssembly to find out the ―DoMath‖ type. ReflectionEmitDemo EmitDemo = new ReflectionEmitDemo(); Assembly EmitAssembly = EmitDemo.CreateAssembly(); System.Type MathType = EmitAssembly.GetType("DoMath"); Next, we prepare the parameters for the ― Sum‖ method, and create an instance of the ―DoMath‖ type on which we do the Invoke. We call the Type.InvokeMember() method to invoke the ― Sum‖ method. In the example below, we’ve passed the parameters 5 and 9. object[] Parameters = new object [2]; Parameters[0] = Parameters[1] = (object) (5); (object) (9); object EmitObj = Activator.CreateInstance(MathType,false); object Result = MathType.InvokeMember("Sum", BindingFlags.InvokeMethod ,null,EmitObj,Parameters); Console.WriteLine ("Sum of {0}+{1} is {2}", Parameters[0],Parameters[1],Result.ToString ()); The output is: Sum of 5+9 is 14 Here is the example code: Collapse using System; using System.Reflection; namespace ConsoleApplication1 { public class EmitDemoTest { static void Main() { ReflectionEmitDemo EmitDemo = new ReflectionEmitDemo(); Assembly EmitAssembly = EmitDemo.CreateAssembly(); System.Type MathType = EmitAssembly.GetType("DoMath"); object[] Parameters = new object [2]; Parameters[0] = (object) (5); Parameters[1] = (object) (9); object EmitObj = Activator.CreateInstance (MathType,false); object Result = MathType.InvokeMember("Sum", BindingFlags.InvokeMethod ,null,EmitObj,Parameters); Console.WriteLine("Sum of {0}+{1} is {2}", Parameters[0],Parameters[1],Result.ToString()); Console.ReadLine(); } } } The attached ZIP file contains a Windows application which lets you examine the assemblies and its types. Reflection in C# This article is aimed to explain reflection in .NET Framework. Reflection is one of the features of .Net framework and has greater importance during the development of large applications. In brief it is a powerful way of collecting and manipulate information present in application's assemblies and its metadata. Metadata contain all the Type information used by the application. The ability to obtain information at runtime also makes it even more advantageous. When reflection is used along with system.type, it allows the developer to get the valuable information about all the types and about the assemblies. We can even create the instances and then invoke various types that are used across the application. What is Reflection? Reflection is the ability to find out information about objects, the application details (assemblies), its metadata at run-time. This allows application to collect information about itself and also manipulate on itself. It can be used effectively to find all the types in an assembly and/or dynamically invoke methods in an assembly. This includes information about the type, properties, methods and events of an object and to invoke the methods of object Invoke method can be used too. With reflection we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If Attributes (C#) are used in application, then with help of reflection we can access these attributes. It can be even used to emit Intermediate Language code dynamically so that the generated code can be executed directly. How to use Reflection in our applications? System.Reflection namespace contains all the Reflection related classes. These classes are used to get information from any of the class under .NET framework. The Type class is the root of all reflection operations. Type is an abstract base class that acts as means to access metadata though the reflection classes. Using Type object, any information related to methods, implementation details and manipulating information can be obtained. The types include the constructors, methods, fields, properties, and events of a class, along with this the module and the assembly in which these information are present can be accessed and manipulated easily. As mentioned earlier, we can use reflection to dynamically create an instance of any type, bind the type to an existing object, or get the type from an existing object. Once this is done appropriate method can be invoked, access the fields and properties. This can be done by specifying the Type of object or by specifying both assembly and Type of the object that needs to be created. By this the new object created acts like any other object and associated methods, fields and properties can be easily accessed. With reflection we can also find out about various methods associated with newly created object and how to use these object. To find out the attributes and methods associated with an object we can use the abstract class MemberInfo, this class is available under the namespace System.Reflection. Reflection can be used in following different ways to get different information about various Types. All the below mentioned classes are available under the namespace System.Reflection. Assembly Class can be used to get the information and manipulate the assembly. This class allows us to define and load assemblies, load modules that are listed in the assembly manifest, and locate a type from this assembly and create an instance of it. Assembly.GetType or Assembly.GetTypes are the two methods that can be used to get the Type object from assemblies that have not been loaded. To these method name of the Type(s) is passed as the parameter. Type.GetType is used similarly as mentioned above only distinction is that here the assemblies are loaded. Example: The following statement fetches mscorlib assembly information Assembly assemblyInformation = typeof(Object).Module.Assembly; // Loads an assembly using its file name Assembly assemblyInformation = Assembly.LoadFrom("MyApplicationToRu n.exe"); // Fetch the types available in the assembly Type [] assemblyTypeInformation = assemblyInformation.GetTypes (); foreach (Type TypeInformation in assemblyTypeInformation) { Console.WriteLine (TypeInformation.FullName); } As shown above once the Type is obtained, there are many ways you can fetch the information about the members of that type. For example, to find out about all the type's members we can use the Type.GetMembers method, which obtains an array of MemberInfo objects describing each of the members of the current type. Module Class is used for the reflection of the module. This class is used to get information about parent assembly, classes in the module, all the global methods available in the classes. ConstructorInfo Class is used for the reflection of a constructor, and used to fetch the information about constructor also constructor can be invoked. Constructor information like name, parameters, access modifiers, and various implementation details (such as abstract or virtual) can be obtained. Class Objects are created when constructor of a ConstructorInfo is invoked this returns either the GetConstructors or GetConstructor method of a Type object. Example: This program lists all the public constructors of the System.String class. using System; using System.Reflection; class ReflectionConstructorInformation { public static void Main(String[] args) { Type StringTypeObject= typeof(System.String); // Constructors. ConstructorInfo[] ConstructorInformation = StringTypeObject.GetConstructors(BindingFlags.Public | BindingFlags.Instance); foreach (MemberInfo memberInformationDetails in ConstructorInformation) { Console.WriteLine ("{0}{1}", " ", memberInformationDetails); } Console.WriteLine(); } } MethodInfo Class is used to obtain information such as the name, return type, parameters, access modifiers (such as public or private), and implementation details (such as ab,stract or virtual) of a any method inside the class, module, assembly. GetMethods or GetMethod method of a Type are used to on the to obtain the information. FieldInfo Class, as the name suggest this class is used to get the information such as the name, access modifiers (such as public or private) and implementation details (such as static) of a field. Even to get or set field values of a class. EventInfo Class is used to fetch the information about name, event-handler data type, custom attributes, declaring type, and reflected type of an event. This class is also used to add or remove event handlers. PropertyInfo Class is used to fetch the information about the name, data type, declaring type, reflected type, and read-only or writable status of a property. Also we can get or set property values using this class. ParameterInfo Class is used to fetch the information about parameter's name, data type, whether a parameter is an input or output parameter, and the position of the parameter in a method signature. We can GetParameters method in this class that returns an array of ParameterInfo objects representing the parameters of a method, in order. Another important namespace is System.Reflection.Emit Namespace. This name space can be used to create the type at run time and invoke as and when required. Basic usage of this namespace is to write the information to appropriate types. System.Reflection.Emit namespace contains classes that can be used by the compiler or tool to emit metadata and Microsoft intermediate language (MSIL). The compiler or script generators basically use this information.
rate this doc
email this doc
embed this doc
add to folder
digg reddit stumble delicious
flag this doc
95
15
not rated
0
6/1/2008
English
search termpage on Googletimes searched
Preview

Microsoft_Net

sanyam 6/1/2008 | 88 | 5 | 0 | educational
Preview

Wrox - Beginning Visual Basic .NET Database Programming

sanyam 6/1/2008 | 222 | 1190 | 0 | educational
Preview

An Introduction to Programming with C# Threads

alon 7/22/2008 | 340 | 8 | 0 | technology
Preview

Programming_Visual_Basic

sanyam 6/1/2008 | 236 | 121 | 0 | educational
Preview

Dot Net Presentation 4

mayurck291 4/17/2008 | 500 | 56 | 0 | technology
Preview

Dot Net Presentation 2

mayurck291 4/17/2008 | 223 | 56 | 0 | technology
Preview

Dot Net Presentation 6

mayurck291 4/17/2008 | 287 | 58 | 0 | technology
Preview

Notes on Programming in C

ProfessionalDocument 8/2/2008 | 25 | 0 | 0 | technology
Preview

Dot Net Presentation 1

mayurck291 4/17/2008 | 450 | 60 | 1 | technology
Preview

Dot Net Presentation 3

mayurck291 4/17/2008 | 250 | 53 | 0 | technology
Preview

Dot Net Presentation 5

mayurck291 4/17/2008 | 738 | 64 | 0 | technology
Preview

Designated Copyright Agent - PALACE dot NET,

CopyrightAgent 3/30/2008 | 13 | 0 | 0 | legal
Preview

Speaker Notes for the K Introductory Lesson

EPADocs 5/14/2008 | 15 | 0 | 0 | legal
Preview

Designated Copyright Agent - alpha dot net, corp.

CopyrightAgent 3/30/2008 | 96 | 0 | 0 | legal
Preview

Bigbook_26

sanyam 6/1/2008 | 126 | 13 | 0 | educational
Preview

Bigbook_25

sanyam 6/1/2008 | 44 | 4 | 0 | educational
Preview

Bigbook_24

sanyam 6/1/2008 | 55 | 6 | 0 | educational
Preview

Bigbook_23

sanyam 6/1/2008 | 57 | 6 | 0 | educational
Preview

Bigbook_22

sanyam 6/1/2008 | 43 | 7 | 0 | educational
Preview

Bigbook_21

sanyam 6/1/2008 | 46 | 2 | 0 | educational
Preview

Bigbook_20

sanyam 6/1/2008 | 38 | 5 | 0 | educational
Preview

Bigbook_19

sanyam 6/1/2008 | 41 | 4 | 0 | educational
Preview

Bigbook_18

sanyam 6/1/2008 | 49 | 4 | 0 | educational
Preview

Bigbook_17

sanyam 6/1/2008 | 43 | 5 | 0 | educational
invokemember modifier "at runtime" invocation getc11
il emit defineparameter41
argument '2': cannot convert from 'system11
inchestometric11
difference between /t:exe and /t:winexe21
invokemember non-static11
what is the difference between assembly11
assembly assemblyinformation = typeof(object)11
 
review this doc