By the way if you use ILDasmexe to examine the intermediate language IL for

.method private hidebysig static void Main cil managed Construct an array of five Int32 elements. IL_0000 ldc.i4.5 IL_0001 newarr mscorlib System.Int32 Initialize the array's elements with values stored in metadata. IL_000 6 dup IL_000c call void InitializeArray class mscorlib System.Array, valuetype Save the reference to the array in the arr variable. IL_0011 stloc.0 Get the address of arr's 0th element and save it in element. ldelema mscorlib System.Int32 stloc.1 Initialize x to 0. IL_001a...

Calling a Types Method

The easiest way to call a method is to use Type's lnvokeMember method. This method is quite powerful in that it lets you do lots of stuff. There are several overloaded versions of lnvokeMember. I'll discuss the one that has the most parameters the other overloads simply pick defaults for certain parameters, making them easier to call. BindingFlags invokeAttr, How to look up members Binder binder, How to match members and arguments Object target, Object args, CultureInfo culture When you call...

Weak Reference internals

From the preceding discussion, it should be obvious that WeakReference objects don't behave like other object types. Normally, if your application has a root that refers to an object and that object refers to another object, both objects are reachable and the garbage collector can't reclaim the memory either object is using. However, if your application has a root that refers to a WeakReference object, the object referred to by the WeakReference object isn't considered reachable and can be...

Yukon

The next version of Microsoft SQL Server code-named Yukon is an unmanaged application because most of its code is still written in unmanaged C . During initialization, however, Yukon will create a CLR COM server. Yukon allows stored procedures to be written in any managed programming language C , Visual Basic, Smalltalk, and so on . These stored procedures will run in their own AppDomain that has special evidence applied to it prohibiting the stored procedures from adversely affecting the...

Encodings Converting Between Characters and Bytes

In Win32, programmers all too frequently have to write code to convert Unicode characters and strings to Multi-Byte Character Set MBCS characters and strings. I've certainly written my share of this code, and it's very tedious to write and error prone to use. In the CLR, all characters are represented as 16-bit Unicode code values and all strings are composed of 16-bit Unicode code values. This makes working with characters and strings easy at run time. At times, however, you want to save...

Designing a Type That Listens for an Event

The hard work is definitely behind you at this point. In this section, I'll show you how to define a type that uses an event provided by another type. Let's start off by examining the code for the Fax type Pass the MailManager object to the constructor, public Fax MailManager mm Construct an instance of the MailMsgEventHandler delegate that refers to the FaxMsg callback method. Register the callback with MailManager's MailMsg event. mm.MailMsg new This is the method that MailManager will call...

Interoperability with Unmanaged Code

The .NET Framework offers a ton of advantages over other development platforms. However, very few companies can afford to redesign and reimplement all of their existing code. Microsoft realizes this and has constructed the CLR so that it offers mechanisms that allow an application to consist of both managed and unmanaged parts. Specifically, the CLR supports three interoperability scenarios Managed code can call an unmanaged function in a DLL Managed code can easily call functions contained in...

Explicit lnterface Member lmplementations

Interfaces are great because they define a standard way for types to communicate with each other. However, this flexibility comes at the cost of compile-time type safety because most interface methods accept parameters of type System.-Object or return a value whose type is System.Object. Look at the very common lComparable interface This interface defines one method that accepts a parameter of type System.Object. If I define my own type that implements this interface, the type definition might...

Overview Ois

In this chapter, I'll talk about a powerful mechanism that allows you to write more maintainable and robust code exception handling. Here are just a few of the benefits offered by exception handling The ability to keep cleanup code in a localized location, and the assurance that this cleanup code will execute By moving cleanup code out of an application's main logic to a localized location, the application is easier to write, understand, and maintain. The assurance that the cleanup code runs...

Explicitly Unloading Assemblies Unloading an AppDomain

The CLR doesn't support the ability to unload an assembly. Instead, you can unload an AppDomain, which causes all the assemblies contained within it to be unloaded. Unloading an AppDomain is very easy you just call AppDomain's static Unload method, passing it a reference to the AppDomain you want unloaded. Note As I mentioned previously, assemblies that are loaded in a domain-neutral fashion can never be unloaded from an AppDomain. To unload these assemblies, the process must be terminated. The...

Running this program yields the following output

WebName utf-16, HeaderName utf-16, BodyName utf-16 IsBrowserDisplay False, IsBrowserSave True IsMailNewsDisplay False, IsMailNewsSave False WebName unicodeFFFE, HeaderName unicodeFFFE, BodyName unicodeFFFE IsBrowserDisplay False, IsBrowserSave False IsMailNewsDisplay False, IsMailNewsSave False CodePage 65001, WindowsCodePage 1200 WebName utf-8, HeaderName utf-8, BodyName utf-8 IsBrowserDisplay True, IsBrowserSave True IsMailNewsDisplay True, IsMailNewsSave True CodePage 65000, WindowsCodePage...

The Global Assembly Cache

Now that you know how to create a strongly named assembly, it's time to learn how to deploy this assembly and how the CLR uses the information to locate and load the assembly. If an assembly is to be accessed by multiple applications, the assembly must be placed into a well-known directory and the CLR must know to look in this directory automatically when a reference to the assembly is detected. This well-known location is called the global assembly cache GAC , which can usually be found in the...

Explicitly Loading Assemblies

So far, I've shown you how to reflect on the assemblies that are loaded into an AppDomain. Knowing how to do this is useful, but you must remember that the CLR decides when to load an assembly the first time a method is called, the CLR examines the method's IL code to see what types are referenced. The CLR then loads all the assemblies that define the referenced types. If a required assembly is already available in the AppDomain, the CLR knows not to load the assembly again. But let's say you...

Parameterful Properties

In the previous section, the get accessor methods for the properties accepted no parameters. For this reason, I called these properties parameterless properties. These properties are easy to understand because they have the feel of accessing a field. In addition to these fieldlike properties, the CLR also supports what I call parameterful properties, whose get access methods accept one or more parameters. Different programming languages expose parameterful properties in different ways. Also,...

Unhandled Exceptions and Windows Forms

In a Windows Forms application, the System.Windows.Forms.Application class has a static Run method that's responsible for the thread's message loop. This loop dispatches window messages to a private method defined by the System.Windows.Forms.NativeWindow type. This method simply sets up a try catch block and inside the try block, the protected WndProc method is called. If a System.Exception-derived unhandled exception occurs while processing a window message, the catch block calls the window...

Controlling What the CLR Does When an Unhandled Exception Occurs

When a managed thread has an unhandled exception, the CLR examines some settings to determine whether it should launch a debugger. To make this determination, the CLR checks the following registry subkey for the DbgJITDebugLaunchSetting value If this value exists, its value must be one of those listed in Table 18-2. Table 18-2 Possible Values of DbgJITDebugLaunchSetting Table 18-2 Possible Values of DbgJITDebugLaunchSetting Display a dialog box asking the user whether he would like to debug the...

Using the BitArray types indexer is incredibly simple

Allocate a BitArray that can hold 14 bits. BitArray ba new BitArray 14 Turn all the even-numbered bits on by calling the set accessor, for Int32 x 0 x lt 14 x ba x x 2 0 Show the state of all the bits by calling the get accessor. foreach Int32 x 0 x lt 14 x Console.WriteLine Bit x is ba x On Off In the BitArray example, the indexer takes one Int32 parameter, bitPos. All indexers must have at least one parameter, but they can have more. These parameters as well as the return type can be of any...

Obtaining a Reference to a SystemType Object

Reflection is most commonly used to learn about types or to manipulate objects using information that is typically known only at run time, not at compile time. Obviously, this dynamic exploring and manipulation of types and objects comes at a performance hit, so you should use it sparingly. In addition, a compiler can't help you locate and fix programming errors related to type safety when you're using reflection. The System.Type type is your starting point for doing type and object...

Loading the Common Language Runtime

Each assembly that you build can be either an executable application or a DLL containing a set of types components for use by an executable application. Of course, the CLR is responsible for managing the execution of code contained within these assemblies. This means that the .NET Framework must be installed on the host machine. Microsoft has created a redistribution package that you can freely ship to install the .NET Framework on your customers' machines. Eventually, the .NET Framework will...

CLR Hosting

The .NET Framework runs on top of Microsoft Windows. This means that the .NET Framework must be built using technologies that Windows understands. For starters, all managed module and assembly files must use the Windows portable executable PE file format and be either a Windows EXE file or a dynamic-link library DLL . When developing the CLR, Microsoft implemented it as a COM server contained inside a DLL that is, Microsoft defined a standard COM interface for the CLR and assigned GUIDs to this...

The code shown earlier makes extensive use of an EventHandlerSet type As I

public class EventHandlerSet IDisposable The private hash table collection used to maintain the event key delegate value pairs private Hashtable events new Hashtable An index property that gets sets the delegate associated with the passed event object's hash code key public virtual Delegate this Object eventKey Returns null if object is not in set get return Delegate events eventKey set events eventKey value Adds Combines a delegate for the indicated event hash code key public virtual void...

Overview

Before we get into the chapters that explain how to develop programs for the Microsoft .NET Framework, let's discuss the steps required to build, package, and deploy your applications and their types. In this chapter, I'll focus on the basics of how to build components that are for your application's sole use. In Chapter 3, I'll cover the more advanced concepts you'll need to understand, including how to build and use assemblies containing components that are to be shared by multiple...