+ All Categories
Home > Documents > net notes

net notes

Date post: 27-Nov-2014
Category:
Upload: anil-bhimineni
View: 236 times
Download: 3 times
Share this document with a friend
186
This article will help your in understanding .NET and .NET architecture. What is the .NET Framework? The .NET Framework is a new and revolutionary platform created by Microsoft for developing applications . It is a platform for application developers . It is a Framework that supports Multiple Language and Cross language integration. IT has IDE (Integrated Development Environment). Framework is a set of utilities or can say building blocks of your application system. .NET Framework provides GUI in a GUI manner. .NET is a platform independent but with help of Mono Compilation System (MCS). MCS is a middle level interface. .NET Framework provides interoperability between languages i.e. Common Type System (CTS) . .NET Framework also includes the .NET Common Language Runtime (CLR), which is responsible for maintaining the execution of all applications developed using the .NET library. The .NET Framework consists primarily of a gigantic library of code. Definition: A programming infrastructure created by Microsoft for building, deploying, and running applications and services that use .NET technologies, such as desktop applications and Web services. Cross Language integration You can use a utility of a language in another language (It uses Class Language Integration). .NET Framework includes no restriction on the type of applications that are possible. The .NET Framework allows the creation of Windows applications, Web applications, Web services, and lot more. The .NET Framework has been designed so that it can be used from any language, including C#, C++, Visual Basic , JScript, and even older languages such as COBOL. Difference between Visual Studio and Visual Studio .NET Visual Studio Visual Studio It is object based It is object oriented Internet based application - Web Application - Web services - Internet enable application - Third party API - Peer to peer Application All developing facilities in internet based application Poor error handling Exception/Error Advance error handler and debugger Memory Management System Level Task Memory Management Application Domain with help of GC (Garbage Collector) DLL HELL VS .NET has solved DLL HELL Problem Simple explanation of definition used in the above comparision: Web Application
Transcript
Page 1: net notes

This article will help your in understanding .NET and .NET architecture.

  What is the .NET Framework?   The .NET Framework is a new and revolutionary platform created by Microsoft for developing applications.  

It is a platform for application developers. It is a Framework that supports Multiple Language and Cross language integration. IT has IDE (Integrated Development Environment). Framework is a set of utilities or can say building blocks of your application system. .NET Framework provides GUI in a GUI manner. .NET is a platform independent but with help of Mono Compilation System (MCS). MCS is a middle level

interface. .NET Framework provides interoperability between languages i.e. Common Type System (CTS) . .NET Framework also includes the .NET Common Language Runtime (CLR), which is responsible for

maintaining the execution of all applications developed using the .NET library. The .NET Framework consists primarily of a gigantic library of code.

Definition: A programming infrastructure created by Microsoft for building, deploying, and running applications and services that use .NET technologies, such as desktop applications and Web services.   Cross Language integration  You can use a utility of a language in another language (It uses Class Language Integration).   .NET Framework includes no restriction on the type of applications that are possible. The .NET Framework allows the creation of Windows applications, Web applications, Web services, and lot more.   The .NET Framework has been designed so that it can be used from any language, including C#, C++, Visual Basic, JScript, and even older languages such as COBOL.   Difference between Visual Studio and Visual Studio .NET  Visual Studio Visual StudioIt is object based It is object orientedInternet based application - Web Application - Web services - Internet enable application - Third party API - Peer to peer Application

All developing facilities in internet based application

Poor error handling Exception/Error Advance error handler and debuggerMemory Management System Level Task Memory Management Application Domain with help of

GC (Garbage Collector)DLL HELL VS .NET has solved DLL HELL Problem

  Simple explanation of definition used in the above comparision:  Web Application  All websites are example of web application. They use a web server.   Internet Enabled Application  They are desktop application. Yahoo messenger is an example of desktop application.   Peer to Peer  Communication through computers through some system.

Page 2: net notes

  Web Services  It doesn't use web-based server. Internet payment systems are example of web services.   DLL Hell  "DLL Hell" refers to the set of problems caused when multiple applications attempt to share a common component like a dynamic link library (DLL) or a Component Object Model (COM) class.   The reason for this issue was that the version information about the different components of an application was not recorded by the system. (Windows Registry cannot support the multiple versions of same COM component this is called the dll hell problem.)   .Net Framework provides operating systems with a Global Assembly Cache (GAC). This Cache is a repository for all the .Net components that are shared globally on a particular machine. When a .Net component is installed onto the machine, the Global Assembly Cache looks at its version, its public key, and its language information and creates a strong name for the component. The component is then registered in the repository and indexed by its strong name, so there is no confusion between different versions of the same component, or DLL.   Architecture of .NET Framework

Page 3: net notes

  Architecture of CLR

Page 4: net notes

CLS (Common Language Specification)   It is a subset of CTS. All instruction is in CLS i.e. instruction of CTS is written in CLS.   Code Manager  Code manager invokes class loader for execution.   .NET supports two kind of coding   1) Managed Code 2) Unmanaged Code   Managed Code  The resource, which is with in your application domain is, managed code. The resources that are within domain are faster.   The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code.   Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.

Page 5: net notes

  Unmanaged Code   The code, which is developed outside .NET, Framework is known as unmanaged code.   Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code.   Unmanaged code can be unmanaged source code and unmanaged compile code.   Unmanaged code is executed with help of wrapper classes.   Wrapper classes are of two types: CCW (COM callable wrapper) and RCW (Runtime Callable Wrapper).   Wrapper is used to cover difference with the help of CCW and RCW. COM callable wrapper unmanaged code

Page 6: net notes

Runtime Callable Wrapper unmanaged code

Page 7: net notes

Native Code  The code to be executed must be converted into a language that the target operating system understands, known as native code. This conversion is called compiling code, an act that is performed by a compiler.   Under the .NET Framework, however, this is a two - stage process. With help of MSIL and JIT.   MSIL (Microsoft Intermediate Language)   It is language independent code. When you compile code that uses the .NET Framework library, you don't immediately create operating system - specific native code.   Instead, you compile your code into Microsoft Intermediate Language (MSIL) code. The MSIL code is not specific to any operating system or to any language.   JIT (Just-in-Time)   Just - in - Time (JIT) compiler, which compiles MSIL into native code that is specific to the OS and machine architecture being targeted. Only at this point can the OS execute the application. The just - in - time part of the name reflects the fact that MSIL code is only compiled as, and when, it is needed.  

Page 8: net notes

In the past, it was often necessary to compile your code into several applications, each of which targeted a specific operating system and CPU architecture. Often, this was a form of optimization.   This is now unnecessary, because JIT compilers (as their name suggests) use MSIL code, which is independent of the machine, operating system, and CPU. Several JIT compilers exist, each targeting a different architecture, and the appropriate one will be used to create the native code required.   The beauty of all this is that it requires a lot less work on your part - in fact, you can forget about system - dependent details and concentrate on the more interesting functionality of your code.   JIT are of three types:

1. Pre JIT 2. Econo JIT 3. Normal JIT

Pre JIT   It converts all the code in executable code and it is slow   Econo JIT  It will convert the called executable code only. But it will convert code every time when a code is called again.   Normal JIT  It will only convert the called code and will store in cache so that it will not require converting code again. Normal JIT is fast.   Assemblies  When you compile an application, the MSIL code created is stored in an assembly. Assemblies include both executable application files that you can run directly from Windows without the need for any other programs (these have a .exe file extension), and libraries (which have a .dll extension) for use by other applications.   In addition to containing MSIL, assemblies also include meta information (that is, information about the information contained in the assembly, also known as metadata) and optional resources (additional data used by the MSIL, such as sound files and pictures).   The meta information enables assemblies to be fully self - descriptive. You need no other information to use an assembly, meaning you avoid situations such as failing to add required data to the system registry and so on, which was often a problem when developing with other platforms.   This means that deploying applications is often as simple as copying the files into a directory on a remote computer. Because no additional information is required on the target systems, you can just run an executable file from this directory and (assuming the .NET CLR is installed) you're good to go.   Of course, you won't necessarily want to include everything required to run an application in one place. You might write some code that performs tasks required by multiple applications. In situations like that, it is often useful to place the reusable code in a place accessible to all applications. In the .NET Framework, this is the Global Assembly Cache (GAC). Placing code in the GAC is simple - you just place the assembly containing the code in the directory containing this cache.   Garbage Collection (GC)  One of the most important features of managed code is the concept of garbage collection. This is the .NET method of making sure that the memory used by an application is freed up completely when the application is no longer in use.   Prior to .NET this was mostly the responsibility of programmers, and a few simple errors in code could result in large blocks of memory mysteriously disappearing as a result of being allocated to the wrong place in memory. That usually meant a progressive slowdown of your computer followed by a system crash.

Page 9: net notes

  .NET garbage collection works by inspecting the memory of your computer every so often and removing anything from it that is no longer needed. There is no set time frame for this; it might happen thousands of times a second, once every few seconds, or whenever, but you can rest assured that it will happen.   Will try to explain the processing in terms of C# code which is written using .NET Framework.   Step 1- Application code is written using a .NET - compatible language C#.

 

Step 2 - Code is compiled into MSIL, which is stored in an assembly (see Figure 1 - 2).

 

Step 3 - When this code is executed (either in its own right if it is an executable or when it is used from other code), it must first be compiled into native code using a JIT compiler.

 

Step 4 - The native code is executed in the context of the managed CLR, along with any other running applications or processes. 

  Note:  One additional point concerning this process. The C# code that compiles into MSIL in step 2 needn't be contained in a single file. It's possible to split application code across multiple source

Page 10: net notes

code files, which are then compiled together into a single assembly. This extremely useful process is known as linking.   This is because it is far easier to work with several smaller files than one enormous one. You can separate out logically related code into an individual file so that it can be worked on independently and then practically forgotten about when completed.   This also makes it easy to locate specific pieces of code when you need them and enables teams of developers to divide up the programming burden into manageable chunks, whereby individuals can check out pieces of code to work on without risking damage to otherwise satisfactory sections or sections other people are working on.   Conclusion  I hope that this article would have helped you in understanding .NET Framework and have built a simple and clear understanding of .NET.   Have taken some definition and lines from some references for technically explanation and understanding. Your feedback and constructive contributions are welcome.  Please feel free to contact me for feedback or comments you may have about this article.

Check this link for CLR architecture http://en.wikipedia.org/wiki/.NET_Framework

INTERFACE NOTES

C# .Net Tutorial Interfaces   

   This C# Tutorial deals with interfaces in C# .Net. An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public. 

Defining an Interface:   Let us look at a simple example for c# interfaces. In this example interface declares base functionality of node object.

interface INode{ 

string Text { get;set; } 

object Tag { get;set; } 

int Height{ get;

Page 11: net notes

set; } 

int Width{ get;set; } 

float CalculateArea(); 

}

   The above INode interface has declared a few abstract properties and function which should be implemented by the derived classes. 

//Sample for Deriving a class using a C# .Net interface -  c# tutorial

public class Node : INode { 

public Node(){}public string Text{ 

get{   return m_text;} 

set{    m_text = value; } 

private string m_text; public object Tag{ 

get{    return m_tag; } 

set{    m_tag = value; } 

private object m_tag = null; public int Height{ 

get

Page 12: net notes

{    return m_height; } 

set{    m_height = value; } 

private int m_height = 0; public int Width{ 

get{    return m_width; } 

set{    m_width = value; } 

private int m_width = 0; 

public float CalculateArea(){ 

if((m_width<0)||(m_height<0))    return 0; 

return m_height*m_width; 

}

   Now the above code has created a c# class Node that inherits from INode c# interface and implement all its members. A very important point to be remembered about c# interfaces is, if  some interface is inherited, the program must implement all its declared members. Otherwise the c# compiler throws an error.

   The above code was a simple example of c# interface usage. Now this has to be followed with some advanced details of interface building in C# .Net. The previous example used only names of methods or properties that have the same names as in interface. But there is another alternative method for writing the implementation for the members in class. It uses full method or property name e.g. INode.CalculateArea () {// implemetation}.

Multiple Inheritance using C# interfaces:   Next feature that obviously needs to be explained is multiple inheritance using c# interfaces. This can be done using child class that inherits from any number of c# interfaces. The inheritance can also happen with a combination of a C# .Net class and c# interfaces. Now let us see a small piece of code that demonstrate us multiple inheritance using only interfaces as parent data types.

class ClonableNode : INode,ICloneable{ 

Page 13: net notes

public object Clone(){return null; } 

// INode members }

   The above example created a class ClonableNode. It implements all the functionality of INode interface in the same way as it was done in Node class. Also it realizes Clone method only one item of IClonable interface of .NET library.

is Operator for C# .Net interfaces - C# Tutorial:   At last a new C# operator that can be used to define that class should be explained. It is the is operator. Look at the following piece of code:

if(nodeC is INode)     Console.WriteLine("nodeC is object of INode type");else      Console.WriteLine("nodeC isn't object of INode type");

   In example nodeC object was created as ClonableNode type, but when we run program "if operator" returns true. It means that nodeC also is of INode type. 

   The Sample Source is downloadable here. An attached example can be compiled using .NET console. You only need to type a filename of your .cs file before csc command and it creates an executable version of it.

ENUMERATION

An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. For example, assume that you have to define a variable whose value will represent a day of the week. There are only seven meaningful values which that variable will ever store. To define those values, you can use an enumeration type, which is declared by using the enum keyword.

VB

C#

C++

F#

JScript

Copy

Page 14: net notes

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };

By default the underlying type of each element in the enum is int. You can specify another integral numeric type by using a colon, as shown in the previous example. For a full list of possible types, see enum (C# Reference).

The following are advantages of using an enum instead of a numeric type:

You clearly specify for client code which values are valid for the variable. In Visual Studio, IntelliSense lists the defined values.

When you do not specify values for the elements in the enumerator list, the values are automatically incremented by 1. In the previous example, Days.Sunday has a value of 0, Days.Monday has a value of 1, and so on. When you create a new Days object, it will have a default value of Days.Sunday (0) if you do not explicitly assign it a value. When you create an enum, select the most logical default value and give it a value of zero. That will cause all enums to have that default value if they are not explicitly assigned a value when they are created.

If the variable meetingDay is of type Days, then (without an explicit cast) you can only assign it one of the values defined by Days. And if the meeting day changes, you can assign a new value from Days to meetingDay:

VB

C#

C++

F#

JScript

Copy

Days meetingDay = Days.Monday;

//...

meetingDay = Days.Friday;

Page 15: net notes

Note

It is possible to assign any arbitrary integer value to meetingDay. For example, this line of code does not produce an

error: meetingDay = (Days) 42. However, you should not do this because the implicit expectation is that an enum

variable will only hold one of the values defined by the enum. To assign an arbitrary value to a variable of an

enumeration type is to introduce a high risk for errors.

You can assign any values to the elements in the enumerator list of an enumeration type, and you can also use computed values:

VB

C#

C++

F#

JScript

Copy

enum MachineState

{

PowerOff = 0,

Running = 5,

Sleeping = 10,

Hibernating = Sleeping + 5

}

Enumeration Types as Bit Flags

Page 16: net notes

You can use an enumeration type to define bit flags, which enables an instance of the enumeration type to store any combination of the values that are defined in the enumerator list. (Of course, some combinations may not be meaningful or allowed in your program code.)

You create a bit flags enum by applying the System.FlagsAttribute attribute and defining the values appropriately so that AND, OR, NOT and XOR bitwise operations can be performed on them. In a bit flags enum, include a named constant with a value of zero that means "no flags are set." Do not give a flag a value of zero if it does not mean "no flags are set".

In the following example, another version of the Days enum, which is named Days2, is defined. Days2 has the Flags attribute and each value is assigned the next greater power of 2. This enables you to create a Days2 variable whose value is Days2.Tuesday and Days2.Thursday.

VB

C#

C++

F#

JScript

Copy

[Flags]

enum Days2

{

None = 0x0,

Sunday = 0x1,

Monday = 0x2,

Tuesday = 0x4,

Wednesday = 0x8,

Thursday = 0x10,

Friday = 0x20,

Saturday = 0x40

}

class MyClass

Page 17: net notes

{

Days2 meetingDays = Days2.Tuesday | Days2.Thursday;

}

To set a flag on an enum, use the bitwise OR operator as shown in the following example:

VB

C#

C++

F#

JScript

Copy

// Initialize with two flags using bitwise OR.

meetingDays = Days2.Tuesday | Days2.Thursday;

// Set an additional flag using bitwise OR.

meetingDays = meetingDays | Days2.Friday;

Console.WriteLine("Meeting days are {0}", meetingDays);

// Output: Meeting days are Tuesday, Thursday, Friday

// Remove a flag using bitwise XOR.

meetingDays = meetingDays ^ Days2.Tuesday;

Console.WriteLine("Meeting days are {0}", meetingDays);

Page 18: net notes

// Output: Meeting days are Thursday, Friday

To determine whether a specific flag is set, use a bitwise AND operation, as shown in the following example:

VB

C#

C++

F#

JScript

Copy

// Test value of flags using bitwise AND.

bool test = (meetingDays & Days2.Thursday) == Days2.Thursday;

Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not");

// Output: Thursday is a meeting day.

For more information about what to consider when you define enumeration types with the System.FlagsAttribute attribute, see System.Enum.

Using the System.Enum Methods to Discover and Manipulate Enum Values

All enums are instances of the System.Enum type. You cannot derive new classes from System.Enum, but you can use its methods to discover information about and manipulate values in an enum instance.

Page 19: net notes

VB

C#

C++

F#

JScript

Copy

string s = Enum.GetName(typeof(Days), 4);

Console.WriteLine(s);

Console.WriteLine("The values of the Days Enum are:");

foreach (int i in Enum.GetValues(typeof(Days)))

Console.WriteLine(i);

Console.WriteLine("The names of the Days Enum are:");

foreach (string str in Enum.GetNames(typeof(Days)))

Console.WriteLine(str);

For more information, see System.Enum.

You can also create a new method for an enum by using an extension method. For more information, see How to: Create a New Method for an Enumeration (C# Programming Guide).

See Also

Referenceenum (C# Reference)

System.Enum

Page 20: net notes

ConceptsC# Programming Guide

Community Content Add

FAQ

Always use Hexadecimal for flag enums

Using decimal for flag enums is more confusing than hexadecimal. The reason has to do with bit alignment. When we create a flag enum, we create a set of numeric values, each of which has one bit set. There is a hexadecimal pattern that makes this easy to see: $00x1, 0x2, 0x4, 0x8 for the first 4 bits, $0 $00x10, 0x20, 0x40, 0x80 for the next 4 bits,$0 $00x100, 0x200, ... and so on$0 $0$0 $0 $0Additionally, hexadecimal makes it easier to see the combination of bits. In this case, a bit of training in hexadecimal pays off tremendously.  Combining 0x10 and 0x20 produces 0x30; no fancy math is needed. Combining 0x4 and 0x8 produces 0xC: one only has to know that 'C' represents 12. Each 4 bits in a flag combined enum value is isolated to a single hexadecimal digit; we have no such advantage with decimal.$0

History

2/1/2011 Frank Hileman

Remove a flag using XOR is confusing // Remove a flag using bitwise XOR.meetingDays = meetingDays ^ Days2.Tuesday;Console.WriteLine("Meeting days are {0}", meetingDays);// Output: Meeting days are Thursday, Friday & ~ Days.Sunday & ~ Days.Sunday

The bitwise XOR operator does not remove or clear the Tuesday bit, but toggles it. The following code line does always remove Tuesday: 

meetingDays = meetingDays & ~ Days.Tuesday;

History

11/23/2010 Jan Hugo van Toor

Sample code for [Flags] is confusing for newcomers Just a quick note for developers that are starting to code using Bitwise Operators.

As noted "power of 2" values must be used as flag values.

The example below causes may lead to programming error using Hexadecimal values instead of Decimal.0x0, 0x1, 0x2, 0x4.. the sequence seems to be doubling then move from 0x8 to 0x10.

0x10 is 16 in decimal so it's correct and will work fine.

Using Decimal values will work the same way and will be better to understand without doing the math

to check the next hexadecimal value of the sequence.

Page 21: net notes

enum Days2 { None = 0, Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64 }

Don't forget that if the value 0 or 0x0 for "None" constant is used in a bitwise AND operation

to test for a flag in conjunction to other constants the result will always be Zero

CALL BY VALUE AND CALL BY REFERENCE.

By Value:

void aMethod(aParameter p) { }

When passing by value a temporary COPY is made in memory taking up space and making any changes to the variable useless outside of the aMethod scope. Once control returns to the calling procedure any changes to the variable will not be recognized, and you will still have the original variable.

By Reference:

void aMethod(aParameter& p) { }

NOTE: the & can be place either against the parameter type, against the parameter name, or there can be a space on either side.

This essentially passes a pointer, but not the same kind of pointer you would get when creating a:Variable* v;That is why it is called by reference, since that is what you have, p now acts as if it were the parameter just like in the by value way, but any changes affect the original and stay changed outside of the aMethod scope.

C# Concepts: Value vs Reference TypesJoseph Albahari

IntroductionOne area likely to cause confusion for those coming from a Java or VB6 background is the distinction between value types and reference types in C#. In particular, C# provides two types—class and struct, which are almost the same except that one is a reference type while the other is a value type. This article explores their essential differences, and the practical implications when programming in C#.

This article assumes you have a basic knowledge of C#, and are able to define classes and properties.

Page 22: net notes

First, What Are Structs?Put simply, structs are cut-down classes. Imagine classes that don’t support inheritance or finalizers, and you have the cut-down version: the struct. Structs are defined in the same way as classes (except with the struct keyword), and apart from the limitations just described, structs can have the same rich members, including fields, methods, properties and operators. Here’s a simple struct declaration:

struct Point{ private int x, y; // private fields

public Point (int x, int y) // constructor { this.x = x; this.y = y; }

public int X // property { get {return x;} set {x = value;} }

public int Y { get {return y;} set {y = value;} }}

Value and Reference TypesThere is another difference between structs and classes, and this is also the most important to understand. Structs are value types, while classes are reference types, and the runtime deals with the two in different ways. When a value-type instance is created, a single space in memory is allocated to store the value. Primitive types such as int, float, bool and char are also value types, and work in the same way. When the runtime deals with a value type, it's dealing directly with its underlying data and this can be very efficient, particularly with primitive types.

With reference types, however, an object is created in memory, and then handled through a separate reference—rather like a pointer. Suppose Point is a struct, and Form is a class. We can instantiate each as follows:

Point p1 = new Point(); // Point is a *struct*Form f1 = new Form(); // Form is a *class*

In the first case, one space in memory is allocated for p1, wheras in the second case, two spaces are allocated: one for a Form object and another for its reference (f1). It's clearer when we go about it the long way:

Form f1; // Allocate the referencef1 = new Form(); // Allocate the object

If we copy the objects to new variables:

Point p2 = p1;Form f2 = f1;

p2, being a struct, becomes an independent copy of p1, with its own separate fields. But in the case of f2, all we’ve copied is a reference, with the result that both f1 and f2 point to the same object.

This is of particular interest when passing parameters to methods. In C#, parameters are (by default) passed by value, meaning that they are implicitly copied when passed to the method. For value-type parameters, this means physically copying the instance (in the same way p2 was copied), while for reference-types it means copying a reference (in the same way f2 was copied). Here is an example:

Page 23: net notes

Point myPoint = new Point (0, 0); // a new value-type variableForm myForm = new Form(); // a new reference-type variable

Test (myPoint, myForm); // Test is a method defined below

void Test (Point p, Form f)

{p.X = 100; // No effect on MyPoint since p is a copyf.Text = "Hello, World!"; // This will change myForm’s caption since

// myForm and f point to the same objectf = null; // No effect on myForm

}

Assigning null to f has no effect because f is a copy of a reference, and we’ve only erased the copy.

We can change the way parameters are marshalled with the ref modifier. When passing by “reference”, the method interacts directly with the caller’s arguments. In the example below, you can think of the parameters p and f being replaced by myPoint and myForm:

Point myPoint = new Point (0, 0); // a new value-type variableForm myForm = new Form(); // a new reference-type variable

Test (ref myPoint, ref myForm); // pass myPoint and myForm by reference

void Test (ref Point p, ref Form f)

{p.X = 100; // This will change myPoint’s positionf.Text = “Hello, World!”; // This will change MyForm’s captionf = null; // This will nuke the myForm variable!

}

In this case, assigning null to f also makes myForm null, because this time we’re dealing with the original reference variable and not a copy of it.

Memory AllocationThe Common Language Runtime allocates memory for objects in two places: the stack and the heap. The stack is a simple first-in last-out memory structure, and is highly efficient. When a method is invoked, the CLR bookmarks the top of the stack. The method then pushes data onto the stack as it executes. When the method completes, the CLR just resets the stack to its previous bookmark—“popping” all the method’s memory allocations is one simple operation!

In contrast, the heap can be pictured as a random jumble of objects. Its advantage is that it allows objects to be allocated or deallocated in a random order. As we’ll see later, the heap requires the overhead of a memory manager and garbage collector to keep things in order.

To illustrate how the stack and heap are used, consider the following method:

void CreateNewTextBox(){

TextBox myTextBox = new TextBox(); // TextBox is a class}

In this method, we create a local variable that references an object. The local variable is stored on the stack, while the object itself is stored on the heap:

Page 24: net notes

The stack is always used to store the following two things:

The reference portion of reference-typed local variables and parameters (such as the myTextBox reference)

Value-typed local variables and method parameters (structs, as well as integers, bools, chars, DateTimes, etc.)

The following data is stored on the heap:

The content of reference-type objects.

Anything structured inside a reference-type object.

Memory DisposalOnce CreateNewTextBox has finished running, its local stack-allocated variable, myTextBox, will disappear from scope and be “popped” off the stack. However, what will happen to the now-orphaned object on the heap to which it was pointing? The answer is that we can ignore it—the Common Language Runtime’s garbage collector will catch up with it some time later and automatically deallocate it from the heap. The garbage collector will know to delete it, because the object has no valid referee (one whose chain of reference originates back to a stack-allocated object).1[1] C++ programmers may be a bit uncomfortable with this and may want to delete the object anyway (just to be sure!) but in fact there is no way to delete the object explicitly. We have to rely on the CLR for memory disposal—and indeed, the whole .NET framework does just that!

However there is a caveat on automatic destruction. Objects that have allocated resources other than memory (in particular “handles”, such as Windows handles, file handles and SQL handles) need to be told explicitly to release those resources when the object is no longer required. This includes all Windows controls, since they all own Windows handles! You might ask, why not put the code to release those resources in the object’s finalizer? (A finalizer is a method that the CLR runs just prior to an object’s destruction). The main reason is that the garbage collector is concerned with memory issues and not resource issues. So on a PC with a few gigabytes of free memory, the garbage collector may wait an hour or two before even getting out of bed!

So how do we get our textbox to release that Windows handle and disappear off the screen when we’re done with it? Well, first, our example was pretty artificial. In reality, we would have put the textbox control on a form in order to make it visible it in the first place. Assuming myForm was created earlier on, and is still in scope, this is what we’d typically do:

myForm.Controls.Add (myTextBox);

As well as making the control visible, this would also give it another referee (myForm.Controls). This means that when the local reference variable myTextBox drops out of scope, there’s no danger of the textbox becoming eligible for garbage collection. The other effect of adding it to the Controls collection is that the .NET framework will deterministically call a method called Dispose on all of its members the instant they’re no longer needed. And in this Dispose method, the control can release its Windows handle, as well as dropping the textbox off the screen.

All classes that implement IDisposable (including all Windows Forms controls) have a Dispose method. This method must be called when an object is no longer needed in order to release resources other than memory. There are two ways this happens: - manually (by calling Dispose explicitly) - automatically: by adding the object to a .NET container, such as a Form, Panel, TabPage or UserControl. The container will ensure that when it’s disposed, so are all of its members. Of course, the container itself must be disposed (or in turn, be part of another container).In the case of Windows Forms controls, we nearly always add them to a container – and hence rely on automatic disposal.

The same thing applies to classes such as FileStream—these need to be disposed too. Fortunately, C# provides a shortcut for calling Dispose on such objects, in a robust fashion: the using statement:

using (Stream s = File.Create ("myfile.txt"))

{

...

}

1

Page 25: net notes

This translates to the following code:

Stream s = File.Create ("myfile.txt");

try

{

...

}

finally

{

if (s != null) s.Dispose();

}

The finally block ensurse that Dispose still gets executed should an exception be thrown within the main code block.

What about in WPF?

Most of the elements in WPF don’t wrap unmanaged handles requiring explicit disposal. So you can mostly ignore the disposal with WPF!

A Windows Forms ExampleLet's look a couple more types you’ll come across often in Windows Forms applications. Size is a type used for representing a 2-dimensional extent and Font, as you would expect, encapsulates a font and its properties. You can find them in the .NET framework, in the System.Drawing namespace. The Size type is a struct—rather like Point, while the Font type is a class. We'll create an object of each type:

Size s = new Size (100, 100); // struct = value typeFont f = new Font (“Arial”,10); // class = reference type

and we’ll also create a form. Form is a class in System.Windows.Forms namespace, and is hence a reference type:

Form myForm = new Form();

To set the form's size and font, we can assign the objects s and f to the form via its properties:

myForm.Size = s;myForm.Font = f;

Don't get confused by the double usage of the identifiers Size and Font: now they are referring to members of myForm and not the Size and Font classes. This double usage is acceptable in C# and is applied extensively throughout the .NET framework.

Here's what it now looks like in memory:

Page 26: net notes

As you can see, with s, we've copied over its contents, while in the case of f, we've copied over its reference (resulting in two pointers in memory to the same Font object). This means that changes made via s will not affect the form, while changes made via f, will2[2].

In-Line Allocation

Previously we said that for value-typed local variables, memory is allocated on the stack. So does that mean the newly copied Size struct is also allocated on the stack? The answer is no, because it’s not a local variable! Instead, it’s stored in a field of another object (in this case a form) that’s allocated on the heap. Therefore, it must, too, be allocated on the heap. This mode of storage is called "in-line".

Fun with StructsWe've made a slightly simplifying assumption in the diagrams in that Size and Font are depicted as fields in the Form class. More accurately, they are properties, which are facades for internal representations we don’t get to see. We can imagine their definitions look something like this:

class Form {

// Private field members

Size size;Font font;

// Public property definitions

public Size Size {

get { return size; }set { size = value; fire resizing events }

}

public Font Font{

get { return font; }set { font = value; }

}}

By using properties, the class has an opportunity to fire events when the form’s size or font changes. It provides further flexibility in that other size-related properties, such as ClientSize (the size of a control’s internal area without title bar, borders, or scroll bars) can work in tandem with the same private fields.

But there is a snag. Suppose we want to double the form’s height, through one of its properties. It would seem reasonable to do this :

2

Page 27: net notes

myForm.ClientSize.Height = myForm.ClientSize.Height * 2;

or more simply:

myForm.ClientSize.Height *= 2;

However, this generates a compiler error:

Cannot modify the return value of 'System.Windows.Forms.Form.ClientSize' because it is not a variable

We get the same problem whether we use Size or ClientSize. Let’s look at why.

Imagine ClientSize as a public field rather than a property. The expression myForm.ClientSize.Height would then simply reach through the membership hierarchy in a single step and access the Height member as expected. But since ClientSize is a property, myForm.ClientSize is first evaluated (using the property’s get method), returning an object of type Size. And because Size is a struct (and hence a value-type) what we get back is a copy of the form’s size. And it’s this copy whose size we double! C# realizes our mistake, and generates an error rather than compiling something that it knows won’t work. (Had Size been defined instead as a class, there would have been no problem, since ClientSize’s get accessor would have returned a reference, giving us access to the form’s real Size object.)

So how then do we change the form’s size? You have to assign it a whole new object:

myForm.ClientSize = new Size (myForm.ClientSize.Width, myForm.ClientSize.Height * 2);

There’s more good news in that with most controls we usually size them via their external measurements (Size rather than ClientSize) and for these we also have ordinary integer Width and Height properties that we can get and set!

You might wonder if they could they have saved all this bother by defining Size as a class rather than a struct. But if Size was a class, its Height and Width properties would probably have been made read-only to avoid the complication of having to raise events whenever their values changed (so that the control can know to resize itself). And as read-only properties, you would be forced to go about changing them by creating a new object—so we’d be back to square one!

The arguments passed to function can be of two types namely( http://www.exforsys.com/tutorials/c-language/call-by-

value-and-call-by-reference.html )

1. Values passed

2. Address passed

The first type refers to call by value and the second type refers to call by reference.

For instance consider program1

main()

{

int x=50, y=70;

interchange(x,y);

printf(“x=%d y=%d”,x,y);

}

interchange(x1,y1)

int x1,y1;

Page 28: net notes

{

int z1;

z1=x1;

x1=y1;

y1=z1;

printf(“x1=%d y1=%d”,x1,y1);

}

Here the value to function interchange is passed by value.

Consider program2

main()

{

int x=50, y=70;

interchange(&x,&y);

printf(“x=%d y=%d”,x,y);

}

interchange(x1,y1)

int *x1,*y1;

{

int z1;

z1=*x1;

*x1=*y1;

*y1=z1;

printf(“*x=%d *y=%d”,x1,y1);

}

Here the function is called by reference. In other words address is passed by using symbol & and the value is

accessed by using symbol *.

The main difference between them can be seen by analyzing the output of program1 and program2.

The output of program1 that is call by value is

x1=70 y1=50

x=50 y=70

But the output of program2 that is call by reference is

*x=70 *y=50

x=70 y=50

This is because in case of call by value the value is passed to function named as interchange and there the value got

interchanged and got printed as

Page 29: net notes

x1=70 y1=50

and again since no values are returned back and therefore original values of x and y as in main function namely

x=50 y=70 got printed

But in case of call by reference address of the variable got passed and therefore what ever changes that happened in

function interchange got reflected in the address location and therefore the got reflected in original function call in

main also without explicit return value. So value got printed as *x=70 *y=50 and x=70 y=50

Call-by-reference in C#

So what is "call-by-reference" found in C#, but not in Java.

You don't need "call-by-reference", but sometimes it is useful.

A method that swaps

Our first example is a method, that will exchange (or swap) the values of two integer variables. Swapping values is usually done with this code:

int tmp=i;i=j;j=tmp;

This will work in Java and C#, if the variables i and j are directly accessible. Making a method like this:

private static void swap1(int i,int j) { int tmp=i; i=j; j=tmp;}

and calling it swap1(a,b); for some integers a and b, will not swap the actual parameters since both parameters uses call-by-value. Local copies are swapped, but this has no effect outside the method.

Since we want to swap the actual parameters we will need to specify that they are passed by reference using the modifier ref:

private static void swap2(ref int i,ref int j) { int tmp=i; i=j; j=tmp;}

In addition to this we will also need to specify call-by-reference when calling the method (Forgetting a ref will result in a syntax error):

swap2(ref a,ref b);

Now the use of i in the method swap2 will actually be the same as using the actual parameter a.

using System;class Swap { private static void swap1(int i,int j) { int tmp=i; i=j; j=tmp; } private static void swap2(ref int i,ref int j) { int tmp=i; i=j; j=tmp;

Page 30: net notes

} static void Main() { int a=207; int b=702; Console.WriteLine("a="+a+" b="+b); swap1(a,b); Console.WriteLine("a="+a+" b="+b); swap2(ref a,ref b); Console.WriteLine("a="+a+" b="+b); }}

Running the code in the complete example above will give these 3 lines of output:

1. a=207 b=702 2. a=207 b=702 3. a=702 b=207

What is call-by-reference really?

A simple program can illustrate what a reference really is. Consider this:

using System;class Reference { private static int a=0; private static void mymethod(ref int i) { Console.WriteLine("a="+a+" i="+i); i++; Console.WriteLine("a="+a+" i="+i); a++; Console.WriteLine("a="+a+" i="+i); } static void Main() { mymethod(ref a); }}

Running this program produces these 3 lines of output:

1. a=0 i=0 2. a=1 i=1 3. a=2 i=2

Both a and i are valid inside the method mymethod, but even though the names are different they refer to the very same variable. Changing one will change the other. We should not think of a variable as something that has a name, but rather say that a variable is a memory location, and that this memory location may have more than one name.

This can lead to subtle programming errors, but since we have to explicitly write the modifier ref when calling a method, we are warned.

(It gets more funny when we pass references, and references to references, to objects around. I plan to extend this article with some illuminating examples at a later time)

Page 31: net notes

What's New in CSharp 3.0

Here is a point wise summary of features introduced newly in C# 3.0

Implicitly Typed Local Variables

Local variables can be declared as type ‘var’ which means compiler to determine the actual type based on the data by which its is initialized.

var i = 10; // i is created of type int var name = “MyName” ; // name is created of type string can only be used when declared and initialized in same statement. Cannot be initialized to null. Cannot be used as class members. Mostly used to store anonymous types as in LINQ based programming.

Object & Collection Initializers

Allow assigning values to any accessible members or properties of a type at the time of initiation without invoking the constructor with parameters.

The default constructor gets executed before assigning the values. E.g. Coordinate c1 = new Coordinate {x=1 , y=2}; Used in LINQ query expressions along with anonymous types. Collection Initializers use Object Initializers to specify multiple elements of collection without

calling Add method multiple times.

Extension Methods

Allows adding new methods to existing types without modifying the existing type. Are special kind of static methods but are called as if they are instance methods. The first parameter passed to Extension methods specifies to which type they operate on

preceded by ‘this’ keyword. They cannot access the private variables of type which they are extending. Extension Methods need to defined in a non-nested and non-generic static class. Instance methods take priority over extension methods in case they have same signature.

Anonymous Types

Are of class types which can have only public read-only properties as their members. No other class members like methods are allowed.

They are of reference types and are derived from ‘Object’ class. Internally compiler gives them the name but its not accessible by application code. They have a method scope. Can be initiated directly e.g. new { property1=1, property2=”Hello World”};

Lambda Expressions

Very similar to anonymous methods introduced in C# 2.0. Its an inline expression or statement block which can be used to pass arguments to method call

or assign value to delegate. All lambda expression use lambda operator => where the left side denotes result and right

contains statement block or expression.

Auto-Implemented Properties

Page 32: net notes

Helps in simplifying property declaration in cases where there is no custom logic required in accessors methods.

E.g. public int Price {get; set;}; Internally compiler creates an anonymous field for assigning values.

In my next post on this i will demonstrate these using a code sample.

Other Posts

LINQ : An Introduction ADO.NET : Past, Present & Future Performance Analysis/Tuning of ASP.NET Application Auto Performance Tuning in ASP.NET 2.0 Overview of Interoperability with UnManaged world Tutorial : Perform Web Load testing using Visual Studio Tip : How to change the default assembly information

Inter-Process Communication - Part 1By Hiran Ramankutty

Scope

The purpose of this article is to get the readers familiar with the different mechanisms that are available for communicating between two or more processes. This may also serve as a tutorial for the novice programmer. There might be several good tutorials on this subject, but here I will try to communicate my explorations of this subject. This article may not be technically perfect. Please send your suggestions and queries to .

Introduction

Inter-Process Communication, which in short is known as IPC, deals mainly with the techniques and mechanisms that facilitate communication between processes. Now, why do we need special separate mechanisms or techniques for communicating between processes? Why isn't it possible to have information shared between two processes without using such special mechanisms?

Let us start from something primitive. Imagine you have two glasses completely filled with water. One glass contains hot water and the other contains cold water. What can you do to make the temperature of water in both the glasses equal? The simplest answer will be to mix the water from both the glasses in a glass with much bigger capacity. Once water is mixed, the temperature becomes equal after some time. If one can remember, this will be framed as a problem with some numerical data in a High-School Physics examination. If we go by principles, then the phenomenon here is conduction. If we go by our topic of IPC, then we can say that since the two glasses were full, we had to use another glass with a larger capacity to mix the contents in order to balance their heat energy.

Have you ever wondered about the communication medium used in telephones? What about the blood transporting system in the human body which communicates blood to different parts of the body? What about my fingers which are typing this document? My brain is doing so many things at a time. How is it directing one of my fingers to hit one key and some other finger to hit another key? How is it synchronizing the typing work that is done by both my hands? How is it also directing me to type the letters of a word that are actually coming to my mind?

Page 33: net notes

Don't worry. I am not going to give a class in Biology. But it would be good if one can imagine a few more situations where we are using inter-process communication, though not necessarily in the human body or in a computer program.

So, where are we now? We know that some medium or other is required for communication between different processes. Similarly, when it comes to computer programs, we need some mechanism or medium for communication. Primarily, processes can use the available memory to communicate with each other. But then, the memory is completely managed by the operating system. A process will be allotted some part of the available memory for execution. Then each process will have its own unique user space. In no way will the memory allotted for one process overlap with the memory allotted for another process. Imagine what would happen otherwise!

So, now the question - how do different processes with unique address space communicate with each other? The operating system's kernel, which has access to all the memory available, will act as the communication channel. Similar to our earlier example, where the glass with hot water is one process address space, the glass with cold water is another, and the glass with the larger capacity is the kernel address space, so that we pour both hot water and cold water into the glass with larger capacity.

What next? There are different IPC mechanisms which come into use based on the different requirements. In terms of our water glasses, we can determine the specifics of both pouring the water into the larger glass and how it will be used after beign poured.

Basic IPC

OK, enough of glasses and water. The IPC mechanisms can be classified into the following categories as given below:

a. pipes b. fifos c. shared memory d. mapped memory e. message queues f. sockets

Pipes

Pipes were evolved in the most primitive forms of the Unix operating system. They provide unidirectional flow of communication between processes within the same system. In other words, they are half-duplex, that is, data flows in only one direction. A pipe is created by invoking the pipe system call, which creates a pair of file descriptors. These descriptors point to a pipe inode and the file descriptors are returned through the filedes argument. In the file descriptor pair, filedes[0] is used for reading whereas filedes[1] is used for writing.

Let me explain a scenario where we can use the pipe system call: consider a keyboard-reader program which simply exits after any alpha-numeric character is pressed on the keyboard. We will create two processes; one of them will read characters from the keyboard, and the other will continuously check for alpha-numeric characters. Let us see how the filedes returned by pipe can be of use in this scenario: (Text version: kbdread-pipe.c.txt)

/***** KEYBOARD HIT PROGRAM *****/#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <unistd.h>#include <pthread.h>#include <ctype.h>

int filedes[2];

void *read_char(){

char c;printf("Entering routine to read character.........\n");

Page 34: net notes

while(1) {/* Get a character in 'c' except '\n'. */c = getchar();if(c == '\n')

c = getchar();write(filedes[1], &c, 1);if(isalnum(c)) {

sleep(2);exit(1);

}}

}

void *check_hit(){

char c;printf("Entering routine to check hit.........\n");while(1) {

read(filedes[0], &c, 1);if(isalnum(c)) {

printf("The key hit is %c\n", c);exit(1);

} else {printf("key hit is %c\n", c);

}}

}

int main(){

int i;pthread_t tid1, tid2;pipe(filedes);/* Create thread for reading characters. */i = pthread_create(&tid1, NULL, read_char, NULL);/* Create thread for checking hitting of any keyboard key. */i = pthread_create(&tid2, NULL, check_hit, NULL);if(i == 0) while(1);return 0;

}

Save and compile the program as cc filename.c -lpthread. Run the program and check the results. Try hitting a different key every time.

The read_char function simply reads a character other than '\n' from the keyboard and writes it to filedes[1]. We have the thread check_hit, which continuously checks for the character in filedes[0]. If the character in filedes[0] is an alpha-numeric character, then the character is printed and the program terminates.

One major feature of pipe is that the data flowing through the communication medium is transient, that is, data once read from the read descriptor cannot be read again. Also, if we write data continuously into the write descriptor, then we will be able to read the data only in the order in which the data was written. One can experiment with that by doing successive writes or reads to the respective descriptors.

So, what happens when the pipe system call is invoked? A good look at the manual entry for pipe suggests that it creates a pair of file descriptors. This suggests that the kernel implements pipe within the file system. However, pipe does not actually exist as such - so when the call is made, the kernel allocates free inodes and creates a pair of file descriptors as well as the corresponding entries in the file table which the kernel uses. Hence, the kernel enables the user to use the normal file operations like read, write, etc., which the user does through the file descriptors. The kernel makes sure that one of the descriptors is for reading and another one if for writing.

I am not going to go into the details of the pipe implementation on the kernel side. For further reading, one can refer the books mentioned at the end of this article.

Page 35: net notes

FIFOs

FIFOs (first in, first out) are similar to the working of pipes. FIFOs also provide half-duplex flow of data just like pipes. The difference between fifos and pipes is that the former is identified in the file system with a name, while the latter is not. That is, fifos are named pipes. Fifos are identified by an access point which is a file within the file system, whereas pipes are identified by an access point which is simply an allotted inode. Another major difference between fifos and pipes is that fifos last throughout the life-cycle of the system, while pipes last only during the life-cycle of the process in which they were created. To make it more clear, fifos exist beyond the life of the process. Since they are identified by the file system, they remain in the hierarchy until explicitly removed using unlink, but pipes are inherited only by related processes, that is, processes which are descendants of a single process.

Let us see how a fifo can be used to detect a keypress, just as we did with pipes. The same program where we previously used a pipe can be modified and implemented using a fifo.

(Text version: write-fifo.c.txt)

/***** PROGRAM THAT READS ANY KEY HIT OF THE KEYBOARD*****/#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <unistd.h>#include <pthread.h>#include <ctype.h>#include <sys/stat.h>#include <fcntl.h>#include <errno.h>

extern int errno;

void *read_char(){

char c;int fd;printf("Entering routine to read character.........\n");while(1) {

c = getchar();fd = open("fifo", O_WRONLY);if(c == '\n')

c = getchar();write(fd, &c, 1);if(isalnum(c)) {

exit(1);}close(fd);

}}

int main(){

int i;pthread_t tid1;i = mkfifo("fifo", 0666);if(i < 0) {

printf("Problems creating the fifo\n");if(errno == EEXIST) {

printf("fifo already exists\n");}printf("errno is set as %d\n", errno);

}i = pthread_create(&tid1, NULL, read_char, NULL);if(i == 0) while(1);return 0;

}

Page 36: net notes

Compile this program using cc -o write_fifo filename.c. This program reads characters (keypresses), and writes them into the special file fifo. First the program creates a fifo with read-write permissions using the function mkfifo. See the manual page for the same. If the fifo exists, then mkfifo will return the corresponding error, which is set in errno. The thread read_char continuously tries to read characters from the keyboard.

Note that the fifo is opened with the O_WRONLY (write only) flag .

Once it reads a character other than '\n', it writes the same into the write end of the fifo. The program that detects it is given below: (text version detect_hit.c.txt):

/***** KEYBOARD HIT PROGRAM *****/#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <unistd.h>#include <pthread.h>#include <ctype.h>#include <errno.h>#include <fcntl.h>#include <sys/stat.h>

extern int errno;

void *check_hit(){

char c;int fd;int i;printf("Entering routine to check hit.........\n");while(1) {

fd = open("fifo", O_RDONLY);if(fd < 0) {

printf("Error opening in fifo\n");printf("errno is %d\n", errno);continue;

}i = read(fd, &c, 1);if(i < 0) {

printf("Error reading fifo\n");printf("errno is %d\n", errno);

}if(isalnum(c)) {

printf("The key hit is %c\n", c);exit(1);

} else {printf("key hit is %c\n", c);

}}

}

int main(){

int i;i = mkfifo("fifo", 0666);if(i < 0) {

printf("Problems creating the fifo\n");if(errno == EEXIST) {

printf("fifo already exists\n");}printf("errno is set as %d\n", errno);

}pthread_t tid2;i = pthread_create(&tid2, NULL, check_hit, NULL);if(i == 0) while(1);return 0;

Page 37: net notes

}

Here, again, it first tries to create a fifo which is created if it does not exist. We then have the thread check_hit which tries to read characters from the fifo. If the read character is alphanumeric, the program terminates; otherwise the thread continues reading characters from the fifo.

Here, the fifo is opened with the flag O_RDONLY.

Compile this program with cc -o detect_hit filename.c. Now run the two executables in separate terminals, but in the same working directory. Irrespective of the order in which you run, look for the message fifo already exists on the console. The first program (either of the two) that you run will not give any error message for creation of the fifo. The second program that you run will definitely give you the error for creation of the fifo. In the terminal where you run write_fifo, give input to standard output from your keyboard. You will get the message regarding the key hit on the keyboard on the terminal running the executable detect_hit. Analyze the working of the two programs by hitting several keys.

I have used two different programs for exhibiting the usage of fifos. This can be done within a single program by forking the routines which are called in the two program as threads. But I did this to show that unlike pipes, fifos can be used for communication between unrelated processes.

Now try running the program again. You will get the message that the fifo already exists even when you first run either of the two programs. This shows that fifos are persistent as long as the system lives. That is, the fifos will have to be removed manually - otherwise they will be permanently recognized by the file system. This is unlike pipes which are inherited as long as the process that created the pipe is running. Once this process dies, the kernel also removes the identifiers (file descriptors) for the pipe from the the file tables.

The usage is rather simple and the main advantage is that there is no need for any synchronization mechanism for accesses to the fifo. There are certain disadvantages: they can only be used for communication between processes running on the same host machine. Let us explore other IPC mechanisms to see what have they in store.

Shared Memory

Shared Memory is one of the three kinds of System V IPC mechanism which enables different processes to communicate with each other as if these processes shared the virtual address space; hence, any process sharing the memory region can read or write to it. One can imagine some part of memory being set aside for use by different processes.

The System V IPC describes the use of the shared memory mechanism as consisting of four steps. Taken in order, they are:

Fetching an identifier for the shared memory area - shmget (shared memory get) Using the identifier to get the shared memory address - shmat (shared memory attach), Detaching the shared memory area after use - shmdt (shared memory detach) and Finally using the address to control accesses, permissions, receive information and destroy the shared memory area - shmctl

(shared memory control).

Let us examine the workings of the above system calls. Recall the keyboard hit program; we shall, once again, see another version of it, this time using the system calls associated with the shared memory mechanism.

The code given below creates a shared memory area and stores the information of any key hit on the keyboard. Let us see the code first: (text version: write-shm.c.txt)

#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <errno.h>#include <string.h>#include <ctype.h>

Page 38: net notes

extern int errno;

#define SIZE 1

char *read_key;int shmid;

int shared_init(){

if((shmid = shmget(9999, SIZE, IPC_CREAT | 0666)) < 0) {printf("Error in shmget. errno is: %d\n", errno);return -1;

}if((read_key = shmat(shmid, NULL, 0)) < 0) {

printf("Error in shm attach. errno is: %d\n", errno);return -1;

}return 0;

}

void read_char(){

char c;while(1) {

c = getchar();if(c == '\n') {

c = getchar();}strncpy(read_key, &c, SIZE);printf("read_key now is %s\n", read_key);if(isalnum(*read_key)) {

shmdt(read_key);shmctl(shmid, IPC_RMID, NULL);exit(1);

}}

}

int main(){

if(shared_init() < 0) {printf("Problems with shared memory\n");exit(1);

}read_char();return 0;

}

Here we have a shared memory variable named read_key. The program first initializes the shared memory area read_key. This is done by generating a shared memory identifier shmid using the system call shmget. In the context of the program, the first parameter for shmget is 9999, which is the key. This key is used to allocate a shared memory segment. The second parameter, SIZE (defined as a macro with the value 1), suggests that the shared memory segment will hold only one of the type of the shared memory variable, that is, only 1 character. The IPC_CREAT flag (third parameter) suggests that a new shared memory segment has to be created, with read-write permissions (IPC_CREAT logically OR ed with 0666). This will return a valid shared memory segment identifier on successful allocation. The identifier will be stored in shmid. If shared memory segment allocation fails, then -1 is returned and the errno is set appropriately.

The key which is used to get a shared memory segment can be generated randomly using the built-in function ftok to get a unique key. Refer to the manual page for the usage.

Once the segment identifier is obtained, we have to attach the shared memory segment to some address. This is done with the shmat system call. This uses the segment identifier shmid as the first parameter. The second parameter is the address of the shared memory segment; when this is given as NULL (as in this program), the kernel will choose a suitable address. The

Page 39: net notes

third parameter is the flag specification which can be set if required or left as zero (see man page of shmdt for details). On success the shared memory segment is attached to read_key, otherwise -1 is returned along with the appropriate setting of the errno.

If either shmget or shmat fails, the process terminates. On success from both system calls, we proceed by invoking the read_char function, which reads keyboard inputs other than '\n' ("Enter" key) and copies them to read_key in the shared memory. If the keyboard input is an alphanumeric character, the program stops reading inputs from the keyboard and the process terminates.

We have another program running separately (it does not have to be in the same working directory) in the local system, which tries to read the data written in the shared memory area. The code is given below: (text version: read-shm.c.txt)

#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <errno.h>#include <string.h>#include <ctype.h>

extern int errno;

#define SIZE 1

char *detect_key;int shmid;

int shared_init(){

if((shmid = shmget(9999, SIZE, 0444)) < 0) {printf("Error in shmget. errno is: %d\n", errno);return -1;

}if((detect_key = shmat(shmid, NULL, SHM_RDONLY)) < 0) {

printf("Error in shm attach. errno is: %d\n", errno);return -1;

}// detect_key = NULL;

return 0;}

void detect_hit(){

char c;c = *detect_key;while(1) {

if(c != *detect_key) {if(isalnum(detect_key[0])) {

printf("detect_key is %s\n", detect_key);shmdt(detect_key);shmctl(shmid, IPC_RMID, NULL);exit(1);

} else {printf("detect_key is %s\n", detect_key);

}c = *detect_key;

}}

}

int main(){

if(shared_init() < 0) {printf("Problems with shared memory\n");

Page 40: net notes

exit(1);}detect_hit();return 0;

}

Here, again, we have a shared memory initialization routine, which in fact does not create a new shared memory segment, but rather tries to get access to the existing shared memory segment. Compared to the previous program, the absence of IPC_CREAT flag suggests that we do not have to create a new shared memory segment. Instead, we simply have to get the corresponding segment identifier which can be used to attach the existing shared memory segment to some address. The mode 0444 restricts access to the shared memory segment to 'read only'. If no shared memory segment with key 9999 exists, we will get an error, which will be returned in errno. Once we get a valid identifier, we attach the shared memory segment to an address. While attaching, we use the flag SHM_RDONLY which specifies that the shared memory segment will be available only for reading.

Next, we have the function detect_hit, which checks whether the pressed key was an alphanumeric character. The first program obviously has to run first; otherwise, the second program will show errors during the shared memory initialization, since it would be trying to get the identifier for a non-existent shared memory segment.

The example shown here doesn't require any synchronization of access to the shared memory segment. That is because only one program writes into the shared memory and only one program reads from the shared memory area. But again, there is a problem here. What if the detection program (second one) is started long after some user has started hitting the keys (running the first program)? We will not be able to track the previously hit keys. The solution for this is left as an exercise to the readers.

The entry in /proc/sysvipc/shm gives a list of shared mermory in use. Readers can compare the entries before running, during running and after running the programs. Try to interpret the entry in /proc/sysvipc/shm.

Once the two programs identify an alphanumeric character, they will terminate. As part of that process, the shared memory area is detached by using the system call shmdt. In fact, upon exiting the detaching is done automatically. But the shared memory segment is not destroyed. This has to be done by invoking the system call shmctl, which takes the identifier for the shared memory area as an argument, as well as the command IPC_RMID, which marks the shared memory segment as destroyed. This has to be done, otherwise the shared memory segment will persist in memory or in the swap space.

At this point, observation of the entries in /proc/sysvipc/shm can be very useful. If the shared memory segment is not destroyed, the entries will reflect this. Try this by running the program without shmctl.

This is the fastest IPC mechanism in the System V IPC services. However, the System V shared memory mechanism does not have any kind of scheme to ensure that one sees consistent data in the shared memory region. That is, a process can read a shared memory area at the same time another process is writing to it. The programmer can then come across inconsistent data while executing the programs. This suggests that accesses to the shared memory region have to be mutually exclusive; this is achieved via the use of the semaphore mechanism. We can make the semaphore access the memory region to lock it and then release the semaphore when done.

The shared memory mechanism can be used when the processes access the shared memory areas at different times. One may wonder why we can't make the first process store the data in some file and make another process read the data from the file. But, reading data from a file involves things like:

execution of system calls like open, read and close. accessing the secondary storage device (generally hard disk) which involves I/O operations.

These things are not significant if we have a small amount of data to be read. But when we have large amounts of data stored in a file, then the load of the two activities mentioned above increases significantly and there is a considerable amount of reduction in the performance of the "reading program". This, again, has a solution, which is the use of memory mapping - something I'll discuss at another time.

Page 41: net notes

Conclusion

We have seen the use of the primary IPC mechanisms, and also one of the System V IPC mechanisms. We have seen some simple uses for pipes, fifos, and the shared memory mechanism. But one may come across some very complex programs where these mechanisms will have to be used in a very strict and precise manner. Otherwise, the program along with the programmer, will be dumped to /dev/null. There are still more things to be learned, not only for you but also for me. I shall come up with more in the next part, in which we will explore semaphores, message queues, memory mapping and sockets, and probably try to solve a few practical problems.

Component Object ModelFrom Wikipedia, the free encyclopedia

Jump to: navigation, search

Component Object Model (COM) is a binary-interface standard for software componentry introduced by Microsoft in 1993. It is used to enable interprocess communication and dynamic object creation in a large range of programming languages. The term COM is often used in the Microsoft software development industry as an umbrella term that encompasses the OLE, OLE Automation, ActiveX, COM+ and DCOM technologies.

Page 42: net notes

Contents[hide]

1 Overview 2 History 3 Related technologies

o 3.1 COM+ o 3.2 .NET

4 Internet security 5 Technical details

o 5.1 Interfaces 5.1.1 Classes

o 5.2 Interface Definition Language and type libraries o 5.3 COM as an object framework o 5.4 Registry o 5.5 Reference counting o 5.6 Instantiation o 5.7 Reflection o 5.8 Programming o 5.9 Application and network transparency o 5.10 Threading in COM

6 Criticisms o 6.1 Message pumping o 6.2 Reference counting o 6.3 DLL hell

7 RegFree COM 8 See also 9 References 10 External links

[edit] Overview

The essence of COM is a language-neutral way of implementing objects that can be used in environments different from the one in which they were created, even across machine boundaries. For well-authored components, COM allows reuse of objects with no knowledge of their internal implementation, as it forces component implementers to provide well-defined interfaces that are separate from the implementation. The different allocation semantics of languages are accommodated by making objects responsible for their own creation and destruction through reference-counting. Casting between different interfaces of an object is achieved through the QueryInterface() function. The preferred method of inheritance within COM is the creation of sub-objects to which method calls are delegated.

COM is an interface technology defined and implemented as standard only on Microsoft Windows and Apple's Core Foundation 1.3 and later plug-in API,[1] that in any case implement only a subset of the whole COM interface.[2] For some applications, COM has been replaced at least to some extent by the Microsoft .NET framework, and support for Web Services through the Windows Communication Foundation (WCF). However, COM objects can be used with all .NET languages through .NET COM Interop.

Networked DCOM uses binary proprietary formats, while WCF encourages the use of XML-based SOAP messaging. COM is very similar to other component software interface technologies, such as CORBA and Java Beans, although each has its own strengths and weaknesses. The characteristics of COM make it most suitable for the development and deployment of desktop applications[citation needed], for which it was originally designated.

Page 43: net notes

[edit] History

One of the first methods of interprocess communication in Windows was Dynamic Data Exchange (DDE), first introduced in 1987, that allowed sending and receiving messages in so-called "conversations" between applications.

Antony Williams, one of the most notable thinkers involved in the creation of the COM architecture, later distributed two internal papers in Microsoft that embraced the concept of software components: Object Architecture: Dealing With the Unknown – or – Type Safety in a Dynamically Extensible Class Library in 1988 and On Inheritance: What It Means and How To Use It in 1990. These provided the foundation of many of the ideas behind COM.

Object Linking and Embedding (OLE), Microsoft's first object-based framework, was built on top of DDE and designed specifically for compound documents. It was introduced with Word for Windows and Excel in 1991, and was later included with Windows, starting with version 3.1 in 1992.

An example of a compound document is a spreadsheet embedded in a Word for Windows document: as changes are made to the spreadsheet within Excel, they appear automatically inside the Word document.

In 1991, Microsoft introduced Visual Basic Extensions (VBX) with Visual Basic 1.0. A VBX is a packaged extension in the form of a dynamic-link library (DLL) that allowed objects to be graphically placed in a form and manipulated by properties and methods. These were later adapted for use by other languages such as Visual C++.

In 1993, when version 3.1 of Windows was released, Microsoft released OLE 2 with its underlying object model. The COM Application binary interface (ABI) was the same as the MAPI ABI, which was released in 1992. While OLE 1 was focused on compound documents, COM and OLE 2 were designed to address software components in general. Text conversations and Windows messages had proved not to be flexible enough to allow sharing application features in a robust and extensible way, so COM was created as a new foundation, and OLE changed to OLE2.

In 1994 OLE custom controls (OCXs) were introduced as the successor to VBX controls. At the same time, Microsoft stated that OLE 2 would just be known as "OLE", and that OLE was no longer an acronym, but a name for all of the company's component technologies.

In early 1996, Microsoft found a new use for OLE Custom Controls, expanding their Web browser's capability to present content, renamed some parts of OLE relating to the Internet ActiveX, and gradually renamed all OLE technologies to ActiveX, except the compound document technology that was used in Microsoft Office. Later that year, DCOM was introduced as an answer to CORBA.

[edit] Related technologies

COM was the major software development platform for Windows and, as such, influenced development of a number of supporting technologies.

[edit] COM+

In order for Microsoft to provide developers with support for distributed transactions, resource pooling, disconnected applications, event publication and subscription, better memory and processor (thread) management, as well as to position Windows as an alternative to other enterprise-level operating systems, Microsoft introduced a technology called Microsoft Transaction Server (MTS) on Windows NT 4.

With Windows 2000, that significant extension to COM was incorporated into the operating system (as opposed to the series of external tools provided by MTS) and renamed COM+. At the same time, Microsoft de-emphasized DCOM as a separate entity. Components that made use of COM+ services were handled more directly by the added layer of COM+, in particular by operating system support for interception. In the first release of MTS, interception was tacked on - installing an MTS component would modify the Windows Registry to call the MTS software, and not the component directly.

Windows 2000 also revised the Component Services control panel application used to configure COM+ components.

Page 44: net notes

An advantage of COM+ was that it could be run in "component farms". Instances of a component, if coded properly, could be pooled and reused by new calls to its initializing routine without unloading it from memory. Components could also be distributed (called from another machine). COM+ and Microsoft Visual Studio provided tools to make it easy to generate client-side proxies, so although DCOM was used to actually make the remote call, it was easy to do for developers.

COM+ also introduced a subscriber/publisher event mechanism called COM+ Events, and provided a new way of leveraging MSMQ (inter-application asynchronous messaging) with components called Queued Components. COM+ events extend the COM+ programming model to support late-bound events or method calls between the publisher or subscriber and the event system.

[edit] .NETMain article: .NET Framework

The COM platform has largely been superseded by the Microsoft .NET initiative, and Microsoft now focuses its marketing efforts on .NET. COM was often used to hook up complex, high performance code to front end code implemented in Visual Basic or ASP.

To some extent, COM is now deprecated in favor of .NET.[3] Since .NET provides rapid development tools similar to Visual Basic for both Windows Forms and Web Forms with just-in-time compilation, back-end code can be implemented in any .NET Language including C#, Visual Basic and C++/CLI.

Despite this, COM remains a viable technology with an important software base. As of 2009, Microsoft has no plans for discontinuing either COM or support for COM. It is also ideal for script control of applications such as Office or Internet Explorer since it provides an interface for calling COM object methods from a script rather than requiring knowing the API at compile time. The GUID system used by COM has wide uses any time a unique ID is needed.

Several of the services that COM+ provides have been largely replaced by recent releases of .NET. For example, the System.Transactions namespace in .NET provides the TransactionScope class, which provides transaction management without resorting to COM+. Similarly, queued components can be replaced by Windows Communication Foundation with an MSMQ transport.

There is limited support for backward compatibility. A COM object may be used in .NET by implementing a runtime callable wrapper (RCW).[4] NET objects that conform to certain interface restrictions may be used in COM objects by calling a COM callable wrapper (CCW).[5] From both the COM and .NET sides, objects using the other technology appear as native objects. See COM Interop.

WCF(Window Communication Foundation) solves a number of COM's remote execution shortcomings, allowing objects to be transparently marshalled by value across process or machine boundaries.

[edit] Internet security

Microsoft's idea of embedding active content on web pages as COM/ActiveX components (rather than e.g. Java applets) created a combination of problems in the Internet Explorer web browser that has led to an explosion of computer virus, trojan and spyware infections. These malware attacks mostly depend on ActiveX for their activation and propagation to other computers. Microsoft recognized the problem with ActiveX as far back as 1996 when Charles Fitzgerald, program manager of Microsoft's Java team said "If you want security on the 'Net', unplug your computer. … We never made the claim up front that ActiveX is intrinsically secure."[6]

As COM and ActiveX components are run as native code on the user's machine, there are fewer restrictions on what the code can do. Many of these problems have been addressed by the introduction of "Authenticode" code signing (based on digital signatures), and later by the .NET platform. Another security measure is that, before an ActiveX control is installed, the user is prompted whether to allow the installation or not, enabling the user to disallow the installation of controls from sites that the user does not trust. It is also possible to disable ActiveX controls altogether, or to allow only a selected few.

Page 45: net notes

[edit] Technical details

COM programmers build their software using COM-aware components. Different component types are identified by class IDs (CLSIDs), which are Globally Unique Identifiers (GUIDs). Each COM component exposes its functionality through one or more interfaces. The different interfaces supported by a component are distinguished from each other using interface IDs (IIDs), which are GUIDs too.

COM interfaces have bindings in several languages, such as C, C++, Visual Basic, Delphi, and several of the scripting languages implemented on the Windows platform. All access to components is done through the methods of the interfaces. This allows techniques such as inter-process, or even inter-computer programming (the latter using the support of DCOM).

[edit] Interfaces

All COM components must (at the very least) implement the standard IUnknown interface, and thus all COM interfaces are derived from IUnknown. The IUnknown interface consists of three methods: AddRef() and Release(), which implement reference counting and controls the lifetime of interfaces; and QueryInterface(), which by specifying an IID allows a caller to retrieve references to the different interfaces the component implements. The effect of QueryInterface() is similar to dynamic_cast<> in C++ or casts in Java and C#.

A COM component's interfaces are required to exhibit the reflexive, symmetric, and transitive properties. The reflexive property refers to the ability for the QueryInterface() call on a given interface with the interface's ID to return the same instance of the interface. The symmetric property requires that when interface B is retrieved from interface A via QueryInterface(), interface A is retrievable from interface B as well. The transitive property requires that if interface B is obtainable from interface A and interface C is obtainable from interface B, then interface C should be retrievable from interface A.

An interface consists of a pointer to a virtual function table that contains a list of pointers to the functions that implement the functions declared in the interface, in the same order that they are declared in the interface. This technique of passing structures of function pointers is very similar to the one used by OLE 1.0 to communicate with its system libraries.

COM specifies many other standard interfaces used to allow inter-component communication. For example, one such interface is IStream, which is exposed by components that have data stream semantics (e.g. a FileStream component used to read or write files). It has the expected Read and Write methods to perform stream reads and writes. Another standard interface is IOleObject, which is exposed by components that expect to be linked or embedded into a container. IOleObject contains methods that allow callers to determine the size of the component's bounding rectangle, whether the component supports operations like 'Open', 'Save' and so on.

[edit] Classes

A class is COM's language-independent way of defining a class in the object-oriented sense.

A class can be a group of similar objects or a class is simply a representation of a type of object; it should be thought of as a blueprint that describes the object.

A coclass supplies concrete implementation(s) of one or more interfaces. In COM, such concrete implementations can be written in any programming language that supports COM component development, e.g. Delphi, C++, Visual Basic, etc.

One of COM's major contributions to the world of Windows development is the awareness of the concept of separation of interface from implementation. An extension of this fundamental concept is the notion of one interface, multiple implementations. This means that at runtime, an application can choose to instantiate an interface from one of many different concrete implementations.

Page 46: net notes

[edit] Interface Definition Language and type libraries

Type libraries contain metadata that represent COM types. However, these types must first be described using Microsoft Interface Definition Language.

This is the common practice in the development of a COM component, i.e. to start with the definition of types using IDL. An IDL file is what COM provides that allows developers to define object-oriented classes, interfaces, structures, enumerations and other user-defined types in a language independent manner. COM IDL is similar in appearance to C/C++ declarations with the addition of keywords such as "interface" and "library" for defining interfaces and collections of classes, respectively. IDL also requires the use of bracketed attributes before declarations to provide additional information, such as the GUIDs of interfaces and the relationships between pointer parameters and length fields.

The IDL file is compiled by the MIDL compiler into a pair of forms for consumption from various languages. For C/C++, the MIDL compiler generates a compiler-independent header file containing struct definitions to match the vtbls of the declared interfaces and a C file containing declarations of the interface GUIDs. C++ source code for a proxy module can also be generated by the MIDL compiler. This proxy contains method stubs for converting COM calls into Remote Procedure Calls, thus enabling DCOM.

An IDL file may also be compiled by the MIDL compiler into a type library (.TLB file). The binary metadata contained within the type library is meant to be processed by language compilers and runtime environments (e.g. VB, Delphi, the .NET CLR etc.). The end result of such TLB processing is that language-specific constructs are produced that represent the COM class defined in the .TLB (and ultimately that which was defined in the originating IDL file).

[edit] COM as an object framework

The fundamental principles of COM have their roots in Object-Oriented philosophies. It is a platform for the realization of Object-Oriented Development and Deployment.

Because COM is a runtime framework, types have to be individually identifiable and specifiable at runtime. To achieve this, globally unique identifiers (GUIDs) are used. Each COM type is designated its own GUID for identification at runtime (versus compile time).

In order for information on COM types to be accessible at both compile time and runtime, COM uses type libraries. It is through the effective use of type libraries that COM achieves its capabilities as a dynamic framework for the interaction of objects.

Consider the following example coclass definition in an IDL :

coclass CSomeObject{ [default] interface ISomeInterface; [default, source] dispinterface _IMyObjectEvents;};

The above code fragment declares a COM class named CSomeObject which must implement an interface named ISomeInterface and which supports (not implements) the event interface _IMyObjectEvents.

Ignoring the event interface bit, this is conceptually equivalent to defining a C++ class like this:

class CSomeObject : public ISomeInterface{ ... ... ...};

where ISomeInterface is a C++ pure virtual class.

Page 47: net notes

Referring once again to the MyObject COM class: once a coclass definition for it has been formalized in an IDL, and a Type Library compiled from it, the onus is on the individual language compiler to read and appropriately interpret this Type Library and then produce whatever code (in the specific compiler's language) necessary for a developer to implement and ultimately produce the binary executable code which can be deemed by COM to be of coclass MyObject.

Once an implementation of a COM coclass is built and is available in the system, next comes the question of how to instantiate it. In languages like C++, we can use the CoCreateInstance() API in which we specify the CLSID (CLSID_CSomeObject) of the coclass as well as the interface (specified by the IID IID_ISomeInterface) from that coclass that we want to use to interact with that coclass. Calling CoCreateInstance() like this:

CoCreateInstance(CLSID_CSomeObject,

NULL,

CLSCTX_INPROC_SERVER,

IID_ISomeInterface,

(void**)&pISomeInterface);

is conceptually equivalent to the following C++ code:

ISomeInterface* pISomeInterface = new CSomeObject();

In the second case, the COM sub-system is used to obtain a pointer to an object that implements the ISomeInterface interface and coclass CLSID_CSomeObject's particular implementation of this interface is required. In the first case, an instance of a C++ class CSomeObject that implements the interface ISomeInterface is created.

A coclass, then, is an object-oriented class in the COM world. The main feature of the coclass is that it is (1) binary in nature and consequently (2) programming language-independent.

[edit] RegistryMain article: Windows Registry

In Windows, COM classes, interfaces and type libraries are listed by GUIDs in the registry, under HKEY_CLASSES_ROOT\CLSID for classes and HKEY_CLASSES_ROOT\Interface for interfaces. The COM libraries use the registry to locate either the correct local libraries for each COM object or the network location for a remote service.

Under the key HKCR\clsid, the following are specified:

-> Inprocserver32 = object is to be loaded into a process + Path to file/object and readable nameHKCR\interface: example: ISTREAM, IRPCSTUB, IMESSAGEFILTER connects to a CLSID. You can specify NUMMETHODS and PROXYSTUB(if web-object)HKCR\typelib One or more CLSID can be grouped into type library. it contains parameters for linking in COM. The rest of the info in the COM parts of the REGISTRY, is to give an application/object a CLSID.

[edit] Reference counting

The most fundamental COM interface of all, IUnknown (from which all COM interfaces must be derived), supports two main concepts: feature exploration through the QueryInterface method, and object lifetime management by including

Page 48: net notes

AddRef() and Release(). Reference counts and feature exploration apply to objects (not to each interface on an object) and thus must have a centralized implementation.

The COM specifications require a technique called reference counting to ensure that individual objects remain alive as long as there are clients which have acquired access to one or more of its interfaces and, conversely, that the same object is properly disposed of when all code that used the object have finished with it and no longer require it. A COM object is responsible for freeing its own memory once its reference count drops to zero.

For its implementation, a COM Object usually maintains an integer value that is used for reference counting. When AddRef() is called via any of object's interfaces, this integer value is incremented. When Release() is called, this integer is decremented. AddRef() and Release() are the only means by which a client of a COM object is able to influence its lifetime. The internal integer value remains a private member of the COM object and will never be directly accessible.

The purpose of AddRef() is to indicate to the COM object that an additional reference to itself has been affected and hence it is necessary to remain alive as long as this reference is still valid. Conversely, the purpose of Release() is to indicate to the COM object that a client (or a part of the client's code) has no further need for it and hence if this reference count has dropped to zero, it may be time to destroy itself.

Certain languages (e.g. Visual Basic) provide automatic reference counting so that COM object developers need not explicitly maintain any internal reference counter in their source codes. Using COM in C, explicit reference counting is needed. In C++, a coder may write the reference counting code or use a smart pointer that will manage all the reference counting.

The following is a general guideline calling AddRef() and Release() to facilitate proper reference counting in COM object:

Functions (whether object methods or global functions) that return interface references (via return value or via "out" parameter) should increment the reference count of the underlying object before returning. Hence internally within the function or method, AddRef() is called on the interface reference (to be returned). An example of this is the QueryInterface() method of the IUnknown interface. Hence it is imperative that developers be aware that the returned interface reference has already been reference count incremented and not call AddRef() on the returned interface reference yet another time.

Release() must be called on an interface reference before that interface's pointer is overwritten or goes out of scope. If a copy is made on an interface reference pointer, AddRef() should be called on that pointer. After all, in this case, we are

actually creating another reference on the underlying object. AddRef() and Release() must be called on the specific interface which is being referenced since an object may implement per-

interface reference counts in order to allocate internal resources only for the interfaces which are being referenced. Extra calls to these functions are not sent out to remote objects over the wire; a proxy keeps only one reference on the

remote object and maintains its own local reference count.

To facilitate and promote COM development, Microsoft introduced ATL (Active Template Library) for C++ developers. ATL provides for a higher-level COM development paradigm. It also shields COM client application developers from the need to directly maintain reference counting, by providing smart pointer objects.

Other libraries and languages that are COM-aware include the Microsoft Foundation Classes, the VC Compiler COM Support, VBScript, Visual Basic, ECMAScript (JavaScript) and Borland Delphi.

[edit] Instantiation

COM standardizes the instantiation (i.e. creation) process of COM objects by requiring the use of Class Factories. In order for a COM object to be created, two associated items must exist:

A Class ID. A Class Factory.

Each COM Class or CoClass must be associated with a unique Class ID (a GUID). It must also be associated with its own Class Factory (that is achieved by using a centralized registry). A Class Factory is itself a COM object. It is an object that

Page 49: net notes

must expose the IClassFactory or IClassFactory2 (the latter with licensing support) interface. The responsibility of such an object is to create other objects.

A class factory object is usually contained within the same executable code (i.e. the server code) as the COM object itself. When a class factory is called upon to create a target object, this target object's class id must be provided. This is how the class factory knows which class of object to instantiate.

A single class factory object may create objects of more than one class. That is, two objects of different class ids may be created by the same class factory object. However, this is transparent to the COM system.

By delegating the responsibility of object creation into a separate object, a greater level of abstraction is promoted, and the developer is given greater flexibility. For example, implementation of the Singleton and other creation patterns is facilitated. Also, the calling application is shielded from the COM object's memory allocation semantics by the factory object.

In order for client applications to be able to acquire class factory objects, COM servers must properly expose them. A class factory is exposed differently, depending on the nature of the server code. A server which is DLL-based must export a DllGetClassObject() global function. A server which is EXE-based registers the class factory at runtime via the CoRegisterClassObject() Windows API function.

The following is a general outline of the sequence of object creation via its class factory:

1. The object's class factory is obtained via the CoGetClassObject() API (a standard Windows API).As part of the call to CoGetClassObject(), the Class ID of the object (to be created) must be supplied. The following C++ code demonstrates this:

2. IClassFactory* pIClassFactory = NULL;3.4. CoGetClassObject(CLSID_SomeObject,5. CLSCTX_ALL,6. NULL,7. IID_IClassFactory,8. (LPVOID*)&pIClassFactory);

The above code indicates that the Class Factory object of a COM object, which is identified by the class id CLSID_SomeObject, is required. This class factory object is returned by way of its IClassFactory interface.

9. The returned class factory object is then requested to create an instance of the originally intended COM object. The following C++ code demonstrates this:

10. ISomeObject* pISomeObject = NULL;11.12. if (pIClassFactory)13. {14. pIClassFactory->CreateInstance (NULL,15. IID_ISomeObject,16. (LPVOID*)&pISomeObject);17.18. pIClassFactory->Release();19.20. pIClassFactory = NULL;21. }

The above code indicates the use of the Class Factory object's CreateInstance() method to create an object which exposes an interface identified by the IID_ISomeObject GUID. A pointer to the ISomeObject interface of this object is returned. Also note that because the class factory object is itself a COM object, it needs to be released when it is no longer required (i.e. its Release() method must be called).

The above demonstrates, at the most basic level, the use of a class factory to instantiate an object. Higher level constructs are also available, some of which do not even involve direct use of the Windows APIs.

Page 50: net notes

For example, the CoCreateInstance() API can be used by an application to directly create a COM object without acquiring the object's class factory. However, internally, the CoCreateInstance() API itself will invoke the CoGetClassObject() API to obtain the object's class factory and then use the class factory's CreateInstance() method to create the COM object.

VBScript supplies the New keyword as well as the CreateObject() global function for object instantiation. These language constructs encapsulate the acquisition of the class factory object of the target object (via the CoGetClassObject() API) followed by the invocation of the IClassFactory::CreateInstance() method.

Other languages, e.g. PowerBuilder's PowerScript may also provide their own high-level object creation constructs. However, CoGetClassObject() and the IClassFactory interface remain the most fundamental object creation technique.

[edit] ReflectionSee also: reflection (computer science)

At the time of the inception of COM technologies, the only way for a client to find out what features an object would offer was to actually create one instance and call into its QueryInterface method (part of the required IUnknown interface). This way of exploration became awkward for many applications, including the selection of appropriate components for a certain task, and tools to help a developer understand how to use methods provided by an object.

As a result, COM Type Libraries were introduced, through which components can describe themselves. A type library contains information such as the CLSID of a component, the IIDs of the interfaces the component implements, and descriptions of each of the methods of those interfaces. Type libraries are typically used by Rapid Application Development (RAD) environments such as Visual Basic or Visual Studio to assist developers of client applications.

[edit] Programming

COM is a binary standard (also said to be language agnostic) and may be developed in any programming language capable of understanding and implementing its binary defined data types and interfaces.

Runtime libraries (in extreme situations, the programmers) are responsible for entering and leaving the COM environment, instantiating and reference counting COM objects, querying objects for version information, coding to take advantage of advanced object versions, and coding graceful degradation of function when newer versions are not available.

[edit] Application and network transparency

COM objects may be instantiated and referenced from within a process, across process boundaries within a computer, and across a network, using the DCOM technology. Out-of-process and remote objects may use marshalling to send method calls and return values back and forth. The marshalling is invisible to the object and the code using the object.

[edit] Threading in COM

In COM, threading issues are addressed by a concept known as "apartment models". Here the term "apartment" refers to an execution context wherein a single thread or a group of threads is associated with one or more COM objects.

Apartments stipulate the following general guidelines for participating threads and objects:

Each COM object is associated with one and only one apartment. This is decided at the time the object is created at runtime. After this initial setup, the object remains in that apartment throughout its lifetime.

A COM thread (i.e., a thread in which COM objects are created or COM method calls are made) is also associated with an apartment. Like COM objects, the apartment with which a thread is associated is also decided at initialization time. Each COM thread also remains in its designated apartment until it terminates.

Threads and objects which belong to the same apartment are said to follow the same thread access rules. Method calls which are made inside the same apartment are performed directly without any assistance from COM.

Threads and objects from different apartments are said to play by different thread access rules. Method calls made across apartments are achieved via marshalling. This requires the use of proxies and stubs.

Page 51: net notes

There are three types of Apartment Models in the COM world: Single-Threaded Apartment (STA), Multi-Threaded Apartment (MTA), and Neutral Apartment. Each apartment represents one mechanism whereby an object's internal state may be synchronized across multiple threads.

The Single-Threaded Apartment (STA) model is a very commonly used model. Here, a COM object stands in a position similar to a desktop application's user interface. In an STA model, a single thread is dedicated to drive an object's methods, i.e. a single thread is always used to execute the methods of the object. In such an arrangement, method calls from threads outside of the apartment are marshalled and automatically queued by the system (via a standard Windows message queue). Thus, there is no worry about race conditions or lack of synchronicity because each method call of an object is always executed to completion before another is invoked.

If the COM object's methods perform their own synchronization, multiple threads dedicated to calling methods on the COM object are permitted. This is termed the Multiple Threaded Apartment (MTA). Calls to an MTA object from a thread in an STA are also marshaled. A process can consist of multiple COM objects, some of which may use STA and others of which may use MTA. The Thread Neutral Apartment allows different threads, none of which is necessarily dedicated to calling methods on the object, to make such calls. The only provision is that all methods on the object must be serially reentrant.

[edit] Criticisms

Since COM has a fairly complex implementation, programmers can be distracted by some of the "plumbing" issues.

[edit] Message pumping

When an STA is initialized it creates a hidden window that is used for inter-apartment and inter-process message routing. This window must have its message queue regularly pumped. This construct is known as a message pump. On earlier versions of Windows, failure to do so could cause system-wide deadlocks. This problem is especially nasty

This article contains weasel words, vague phrasing that often accompanies biased or unverifiable information. Such statements should be clarified or removed. (March 2011)

because some Windows APIs initialize COM as part of their implementation, which causes a leak of implementation details.

[edit] Reference counting

Reference counting within COM may cause problems if two or more objects are circularly referenced. The design of an application must take this into account so that objects are not left orphaned.

Objects may also be left with active reference counts if the COM "event sink" model is used. Since the object that fires the event needs a reference to the object reacting to the event, the object's reference count will never reach zero.

Reference cycles are typically broken using either out-of-band termination or split identities. In the out of band termination technique, an object exposes a method which, when called, forces it to drop its references to other objects, thereby breaking the cycle. In the split identity technique, a single implementation exposes two separate COM objects (also known as identities). This creates a weak reference between the COM objects, preventing a reference cycle.

[edit] DLL hellMain article: DLL hell

Because COM components are usually implemented in DLL files and registration allows only single version of a DLL they are subject of "DLL hell" effect. Registration-free COM capability eliminates the problem.

Page 52: net notes

[edit] RegFree COM

RegFree COM (or Registration-Free COM) is a technology introduced with Windows XP that allows Component Object Model (COM) components to store activation metadata and CLSID (Class ID) for the component without using the registry. Instead, the metadata and CLSIDs of the classes implemented in the component are declared in an assembly manifest (described using XML), stored either as a resource in the executable or as a separate file installed with the component.[7] This allows multiple versions of the same component to be installed in different directories, described by their own manifests, as well as XCOPY deployment.[8] This technique cannot be used for EXE COM servers or system-wide components such as MDAC, MSXML, DirectX or Internet Explorer.

During application loading, the Windows loader searches for the manifest.[9] If it is present, the loader adds information from it to the activation context [8] When the COM class factory tries to instantiate a class, the activation context is first checked to see if an implementation for the CLSID can be found. Only if the lookup fails is the registry scanned.[8]

[edit] See also

Portable object (computing) cross language cross platform Object Model definition Distributed Component Object Model (DCOM), extension making COM able to work in networks Common Language Infrastructure current .Net cross language cross platform Object Model CORBA Common Object Request Broker Architecture, open cross language cross platform object model Freedesktop.org D-Bus current open cross language cross platform Object Model GNOME Bonobo deprecated GNOME cross language Object Model KDE DCOP deprecated KDE interprocess and software componentry communication system KDE KPart deprecated KDE component framework XPCOM Mozilla applications cross Platform Component Object Model IBM System Object Model SOM, a component system from IBM used in OS/2 Java Beans Java Remote Method Invocation Internet Communications Engine Language binding Foreign function interface Calling convention Name mangling Application programming interface - API Application Binary Interface - ABI Comparison of application virtual machines SWIG opensource automatic interfaces bindings generator from many languages to other languages

[edit] References

This article needs additional citations for verification.Please help improve this article by adding reliable references. Unsourced material may be challenged and removed. (April 2008)

1. ̂ http://developer.apple.com/library/mac/#documentation/CoreFoundation/Conceptual/CFPlugIns/Concepts/conceptual.html%23//apple_ref/doc/uid/20001160-102910-BAJFDFFC

2. ̂ "Plug-ins and Microsoft’s COM". Apple Inc.. http://developer.apple.com/library/mac/#documentation/CoreFoundation/Conceptual/CFPlugIns/Concepts/com.html#//apple_ref/doc/uid/20001158-CJBEJBHH. Retrieved 2010-10-05.

3. ̂ Integration and Migration of COM+ services to WCF 4. ̂ Runtime Callable Wrapper — MSDN Library 5. ̂ COM callable wrapper — MSDN Library 6. ̂ http://replay.waybackmachine.org/20060810235058/http://www.javaworld.com/javaworld/jw-03-1997/jw-03-

component.web97.html 7. ̂ "Assembly Manifests". MSDN. http://msdn.microsoft.com/en-us/library/aa374219(VS.85).aspx. Retrieved 2009-11-05. 8. ^ a b c Dave Templin. "Simplify App Deployment with ClickOnce and Registration-Free COM". MSDN Magazine.

http://msdn.microsoft.com/en-us/magazine/cc188708.aspx. Retrieved 2008-04-22.

Page 53: net notes

9. ̂ "Concepts of Isolated Applications and Side-by-side Assemblies". MSDN. http://msdn.microsoft.com/en-us/library/ms235531(VS.80).aspx. Retrieved 2009-11-05.

"COM: A Brief Introduction (powerpoint)" . http://www.cs.ucr.edu/~dberger/Documents/Presentations/com-intro.ppt. Retrieved March 7, 2006.

Box, Don (1998). Essential COM. Addison-Wesley. ISBN 0-201-63446-5. Chappell, David (1996). Understanding ActiveX and OLE. Microsoft Press. ISBN 978-1572312166. "Integration and Migration of COM+ services to WCF".

[edit] External links

Microsoft COM Technologies Interview with Tony Williams, Co-Inventor of COM (Video Webcast, August 2006) A concise technical overview of COM from master's thesis Info: Difference Between OLE Controls and ActiveX Controls from Microsoft TypeLib Data Format Specification (unofficial) with open source dumper utility. The COM / DCOM Glossary

Component Object Model (COM)

The demand for businesses to deploy solutions across multiple servers is bound to increase. With the growth and acceptance of the Internet, businesses have come to think of their applications and information be connected and distributed across multiple servers from remote locations. Also data can be processed and accessed through the use of Web browsers and by user interfaces. But a number of problems stands on the way towards developing and deploying mission-critical business applications on several server systems. These applications are named as distributed software applications. They are communication issues among different programming languages and platforms and security. There are a few promising technologies for promoting these critical applications.. Microsoft has come out with a new technology called as Component Object Model (COM) that addresses these problems towards the goal of design of distributed software components.

What is COM

COM is an outgrowth of the OO technology. It is a specification that is based on a binary standard for reuse through interfaces. That is, components, which are pre-compiled blocks of code, written for COM can be reused without any dependencies on the language in which they are coded. The programming language may be Visual Basic, C++ etc.

COM uses system-level code that is implemented in the form of dynamic link libraries, which are collectively called COM library. The COM library consists of several application programming interface (API) functions that are necessary for COM components to do various tasks. COM library is responsible for locating and activating server applications. With client applications, COM APIs contains the necessary functions for instantiating objects that the client want to use. Also the COM library provides locator services using the System Control Manager (SCM), which also provides

Page 54: net notes

transparent remote procedure calls when an object is executing out-of-process in a local or remote server.

Component-based Development (CBD)

CBD came from OO software development methodology towards facilitating software reusability in larger scale. Suppose there is an object and we want to use that in an application. For that, we have to cut and paste the code in the application. If there is any changes made in the object, we have to search for all the object copies in the application to insert the relevant changes. This becomes cumbersome when there are more applications with more copies of the same object. Here comes the idea of designing components as a robust solution. A component can be technically defined as a coarse-grained object. It is also defined as a reusable software module, which displays its services through interfaces for use by client software. On using a component, which is stored in a single place, applications can use the object directly from the component and get the same functionality. Thus both classes, where objects get derived from and components provide same type of services. Classes pro! vide services to single applications because they can not communicate with other applications due to the differences in language and platform, while components provide services to numerous applications irrespective of the languages used. There came a number of architecture for developing both client-side and server-side components. They are OMG's CORBA, Sun's JaveBeans and Enterprise JavaBeans and Microsoft's COM. Thus the world is full of software components, which in turn can be of greater use for hundreds of different applications. As both CORBA and COM supports language independence, a different software vendor can create components using different programming languages without any integration problems. Click for an overview of components .

Advantages of COM

1. COM promotes component-based software development - before component-based development came, software programs have been coded using procedural programming paradigm, which supports linear form of program execution. But component-based program development comes with a number of advantages, such as the ability to use pre-packaged components and tools from third party vendors into an application and support for code reusability in other parts of the same application.

2. COM promotes code reusability - standard classes are normally reused in the same application but not to be used easily in other applications. But COM components are designed to separate themselves from single applications and hence can be accessed and used by several different applications without any hassle.

3. COM promotes Object-oriented programming (OOP) - The primary characteristics of OOP are encapsulation, which allows the implementation details of an object to be hidden, polymorphism, which is the ability to exhibit multiple behaviors, and inheritance, which allows for the reuse of existing classes in order to design new and more specialized classes. Among these, encapsulation is one of COM's most important characteristics. Encapsulation helps to hide how an object has implemented a method internally. This ultimately helps to incorporate more vigorously implemented or advanced implementation into an object at later time without affecting the client which uses it.

Page 55: net notes

4. COM comprises the necessary mechanisms for COM components to communicate with each other - In the normal case, two components coded using two different programming languages can not communicate with each other. But COM can make it possible for different language components, which adhere to the COM specification, to interact with each other and hence COM is language-independent.

5. COM helps to access components loaded in different machines on the network - COM component can reside anywhere on our computer or even on another computer connected to a network. That is, applications using COM can access and share COM components regardless of their locations. Thus COM abstracts away the nitty-gritty of clients to locate COM components anywhere in the network. Thus COM provides location transparency and COM components are location independent.

COM Interfaces

Components, especially server-side ones, are bound to have their own interfaces. An interface is simply a list of methods a COM component implements and makes them available to consumers. COM interface are immutable. That is, once a COM component has been released with an interface, this interface must never be manipulated. COM interfaces are the mechanisms by which a client contacts, connects and use components. If the client component is using a different language from the one a server component is coded, there will be language problem for interactions. In order to remove this barrier, COM interfaces provide an universal way so that components coded in different languages can communicate with each other. Thus every interface constitutes a binding contract between a COM object (no interface is attached with this) and a COM component with an interface. COM specification makes life easier by allowing a component to publish more than one interface at a time. New interfaces can! be incorporated to support new features of the components while keeping the original interface intact. We have to increment a version number for the new interface. A class module then would need to be implemented for both old and new interfaces in order to support both old clients that rely on the old interface and new clients that can take advantage of the new interface. Thus the immutability factor of COM interfaces can be overcome.

Interface Definition Language (IDL)

To successfully make COM language-independent, the COM interfaces have to coded using IDL. IDL is just a declaration language, not a programming language. The syntax for IDL is almost similar to C++ language. But IDL goes beyond what C++ can offer by being able to define functions that extend process boundaries. IDL provides many vital extensions that allow attributes such as type libraries, co-classes, interfaces, and method parameters to be specified quite elegantly. But if there is no language problem, it is not mandatory to use IDL for defining COM interfaces.

Here comes an model interface definition for a COM component coded using Microsoft IDL.

[ object, uuid (122323FAGAd098776) ] interface IFindSum : IUnknown { import "unknown.idl"

Page 56: net notes

HRESULT SumOfNumbers ( [in] long lnum1, [in] long lnum2, [out, retval] long* sum); }

The interface definition begins with an object attribute. The object attribute is used to identify a COM interface. Then a UUID (universally unique identifier), which provides an unique identifying number ( a string of hexadecimal digits ) for each interface and this number is being generated by an algorithm, which takes into account the unique value from the network card on the programmer's PC and the current system date and time, follows that. The interface keyword is followed by the name of the interface (IFindSum).

The letter I in the interface name helps to identify that this is an interface. Following IFindSum is a colon and then the interface name IUnknown, the base interface and every COM object has to have this interface. IUnknown has three methods that a client can invoke: QueryInterface, AddRef, and Release.

The QueryInterface method is the mechanism that a client uses to discover and navigate the interfaces of a component dynamically. It is the most significant method of all COM interfaces available for a component since this method allows run-time checking of all of these interfaces. When the QueryInterface method provides an interface pointer to a client, the QueryInterface calls the method AddRef. The only way to access a COM object is through a pointer to an interface.

An interface pointer is actually a pointer to a pointer in a virtual table that is implemented in memory. That is, for every class that contains public methods, a virtual table will be created and placed in memory at run time. Virtual tables are generated for each class and not for objects of that class. Each virtual table contains an array of function pointers whose elements contain the address of each specific function that an object can implement. At the top of every virtual table array will be three fundamental methods that make up this IUnknown interface.

The methods AddRef and Release manage reference counting. This reference count is an internal count of the number of clients using a particular COM object . It is possible for several clients to invoke the services available with a COM object at the same time. When a client begins a session with an object, it calls the AddRef method, which increments one to the existing count. Once the session is over, the corresponding Release method gets invoked to decrement one from the existing count.

The next line down is used to locate the definition for the base interface IUnknown The next line identifies the interface method "SumofNumbers". This interface method is designed to return an HRESULT value.

An HRESULT is used with COM to indicate whether a method call is successfully accomplished or not. Almost all COM interfaces return a special 32-bit code, called as HRESULT, from their methods to return status information. It is actually the method COM utilizes to return errors to the caller of the method. The reason for this mechanism is due to the inability of COM to transmit error messages back to the client if there is anything wrong on the server side or on the way to the server. As components are being written using different programming languages and each language follows its own exception mechanisms, COM can not correctly pass on the error messages and hence HRESULT.

Following the HRESULT are three parameters for the interface method SumOfNumbers. The [in] in the first two parameters specifies that these parameters are input values to be passed to the

Page 57: net notes

interface method and the [out, retval] in the last parameter indicates that this parameter returns a value that will be ultimately passed to back to the client.

Windows Registry and Components Environment

COM components may be loaded in different address spaces in the same machine or machine connected with the network. Before an object can be created, the COM runtime must first locate the COM components. The COM runtime is able to locate COM components through the use of Windows registry.

COM components may be out-of-process or in-process. An out-of-process component can effectively be a separate program containing objects. This type runs in its own process space and will thus be largely independent from any client programs. These components are often large applications themselves, and provide access to their objects to make it easy for other programs to create macros or otherwise make use of existing functionality. This can be very beneficial, because the component developer can choose his own threading models. The drawback here is that the developer has to write the code for threading. This work can be handled by automatically COM+ , the latest one from the COM family.

There is also a performance issue. Because the client application is communicating with objects which are in an entirely different process there is quite a bit of overhead. COM steps in between the client and the server and handles all the communication between them. Mainly out-of-process components are useful if we are trying to make use of the objects in a pre-existing application.

An in-process component is one where the objects run inside the client's process. Each client gets its own private copy of the component and hence a copy of all the objects in that component. An in-process component is often called COM DLLs or ActiveX DLLs. In-process component does not have a process of its own and it always runs within the context of another process. Often this other process is the client application itself but may be run within the context of a different process entirely. In this case, we can get performance boost as the component is loaded in the client application itself. There is almost no overhead when client interacts with an object that is running in the same process. The major advantages of having in-process components are stability and increased manageability

Creating a COM object

There is a lot of communication that must occur behind the scenes in order for a COM object to be created. First of all, a client looking for an object has to make a call to an API function called CoCreateInstance with the CLSID for the class, which comprises the particular object. The prefix Co in this function is a typical naming convention for COM runtime API functions. CoCreateInstance in turn as a second step calls another API function called CoGetClassObject. Basically the function CoCreateInstance asks the SCM to search the Windows registry location, which is HKEY_CLASSES_ROOT\CLSID. The function of SCM is to locate the requested class object by using the specified CLSID. The first place the SCM looks to locate the class object is within its own internal database. If the class is not located inside its database, the SCM turns to the system registry as a third step. As soon as the class object is found, the SCM immediately returns to COM an interface pointer referred to as IClassFactory.

Page 58: net notes

Every COM class must have a factory object associated with it. The main purpose of these class objects is to implement the IClassFactory interface. Once the client gets the IClassFactory pointer, two things happen. One, by obtaining a pointer to the IClassFactory, CoCreateInstance can call IClassFactory::CreateInstance in order to create the requested COM object. Once the object is created, a second step occurs: the interface pointer to the IClassFactory gets released.

The interface called IClassFactory's job is to talk to other class objects. Further, CoGetClassObject is a COM class object whose sole purpose is to create a new instance of a different class. Because this COM class creates class objects by implementing the IClassFactory interface, CoGetClassObject is referred to as a class factory.

LockServer

When an object is created it resides in memory. It is the client's job to notify the object when it is no longer needed. The Release method told above can decrement the reference count for the interface. If there are several interfaces for an object, it is possible that the object is still being accessed somewhere else. The idea is that the reference count has to reach zero before the object is to be released from the memory. Releasing objects from memory usually improves performance. Some special clients constantly create and destroy objects, which normally affects the application's performance. The LockServer method allows components to remain in memory by incrementing the reference count by one. Because LockServer keeps a count of one in the reference counter, the object will stay in memory even if it is not being accessed currently. Having the component reside in memory has the advantage of allowing the object to be called without having to go through the process of recre! ating it. But on the other hand, if objects are not destroyed when they are not in use, there will be reduction of system memory resources.

Click for Web resources COM Web resources

Base Class LibraryFrom Wikipedia, the free encyclopedia

Jump to: navigation, search

The Base Class Library (BCL) is a standard library available to all languages using the .NET Framework. .NET includes the BCL in order to encapsulate a large number of common functions, such as file reading and writing, graphic rendering, database interaction, and XML document manipulation, which makes the programmer's job easier. It is much larger in scope than standard libraries for most other languages, including C++, and is comparable in scope to the standard libraries of Java. The BCL is sometimes incorrectly referred to as the Framework Class Library (FCL), which is a superset including the Microsoft.* namespaces.

The BCL is updated with each version of the .NET Framework.

Page 59: net notes

Contents[hide]

1 Namespaces o 1.1 Standardized namespaces o 1.2 Non standardized namespaces

2 See also o 2.1 Other capabilities of the .NET framework

3 References 4 External links

[edit] Namespaces

Some of the namespaces may or may not be officially considered part of the BCL by Microsoft, but all are included as part of the libraries that are provided with Microsoft's implementation of the .NET Framework.

[edit] Standardized namespaces

These are the namespaces that are standardized as of the ECMA 335 and ISO/IEC 23271:2006 standards.[1][2]

System

This namespace includes the core needs for programming. It includes base types like String, DateTime, Boolean, and so forth, support for environments such as the console, math functions, and base classes for attributes, exceptions, and arrays.

System.Collections

Defines many common containers or collections used in programming, such as lists, queues, stacks, hashtables, and dictionaries. It includes support for generics.[3]

System.Diagnostics

Provides the ability to diagnose applications. It includes event logging, performance counters, tracing, and interaction with system processes.[4]

System.Globalization

Provides help for writing internationalized applications. "Culture-related information, including the language, the country/region, the calendars in use, [and] the format patterns for dates, currency, and numbers" can be defined.[5]

System.IO

Enables reading from and writing to different streams, such as files or other data streams. Also provides a connection to the file system.[6]

System.Net

Provides an interface "for many of the protocols used on networks today",[7] such as HTTP, FTP, and SMTP. Secure communication is supported by protocols such as SSL.

System.Reflection

Provides an object view of types, methods, and fields; and "the ability to dynamically create and invoke types".[8] It exposes the API to access the Reflective programming capabilities of CLR.

Page 60: net notes

System.Runtime

Allows management of the runtime behavior of an application or the CLR. Some of the included abilities are interoperable with COM or other native code, writing distributed applications, and serializing objects into binary or SOAP.[9]

System.Security

"Provides the underlying structure of the common language runtime security system."[10] This namespace allows security to be built into applications based on policy and permissions. It provides services such as cryptography.

System.Text

Supports various encodings, regular expressions, and a more efficient mechanism for manipulating strings (StringBuilder).[11]

System.Threading

Helps facilitate multithreaded programming. It allows the synchronizing of "thread activities and access to data" and provides "a pool of system-supplied threads."[12]

System.Xml

"Provides standards-based support for processing XML,"[13] including reading, writing, schemas, serialization, searching, and transforming.

[edit] Non standardized namespaces

These are the namespaces that are not standardized as of the ECMA and/or ISO standards, and are specific to Microsoft implementation. However, even if implementing them is not mandatory, some of them have been implemented completely or partially by other .NET implementations.

System.CodeDom

This library provides the ability to create code and run it, at runtime.[14]

System.ComponentModel

Provides the ability to implement the run-time and design-time behavior of components and controls. It contains the infrastructure "for implementing attributes and type converters, binding to data sources, and licensing components."[15]

System.Configuration

Provides the infrastructure for handling configuration data.[16]

System.Data

This namespace represents the ADO.NET architecture, which is a set of computer software components that can be used by programmers to access data and data services.[17]

System.Deployment

Allows customization of the way applications upgrade when using ClickOnce.[18][19]

System.DirectoryServices

Provides easy access to Active Directory from managed code.[20]

System.Drawing

Page 61: net notes

Provides access to GDI+ graphics functionality, including support for 2D and vector graphics, imaging, printing, and text services.[21]

System.EnterpriseServices

"Provides .NET objects with access to COM+ services making the .NET Framework objects more practical for enterprise applications."[22]

System.Linq

Defines the IQueryable<T> interface and related methods, that lets LINQ providers to be plugged in.[23]

System.Linq.Expressions

Allows Delegates and Lambda expressions to be represented as expression trees, so that the high-level code can be examined and processed at runtime.[24]

System.Management

Allows querying for system information, "such as how much free space is left on the disk, what is the current CPU utilization, which database a certain application is connected to, and much more."[25]

System.Media

Provides the ability to play system sounds and .wav files.[26]

System.Messaging

Provides the ability "to connect to, monitor, and administer message queues on the network and send, receive, or peek messages."[27] .NET Remoting is another name for some of the functionality provided. This namespace is being superseded by Windows Communication Foundation.

System.Resources

Allows management of resources in the application in order to internationalize an application for different cultures and languages.[28]

System.ServiceProcess

Allows the creation of applications that run as a service within Windows.[29]

System.Timers

"Allows you to raise an event on a specified interval."[30]

System.Transactions

Provides support for local or distributed transactions.[31]

System.Web

Provides various web related functionality. It enables browser-server communication and the creating XML Web services. Most or all of these libraries are referred to as the ASP.NET architecture.[32]

System.Windows.Forms

Page 62: net notes

This namespace contains the Windows Forms architecture which provides access to the native Windows interface elements by wrapping the existing Windows API. This allows for writing graphical applications for Windows from within managed code.[33] This system is being superseded by the Windows Presentation Foundation.

.NET Framework Class LibraryOther Versions

The .NET Framework class library is a library of classes, interfaces, and value types that provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built.

Namespaces

The .NET Framework class library provides the following namespaces, which are documented in detail in this reference.

Accessibility

Contains types that are part of a managed wrapper for the Component Object Model (COM) accessibility interface.

Microsoft.Aspnet.Snapin

Contains classes that are necessary for the ASP.NET management console application to interact with the Microsoft Management Console (MMC).

Microsoft.Build.BuildEngine

Contains the classes that represent the MSBuild engine.

Microsoft.Build.Construction

Contains types that the MSBuild object model uses to construct project roots with unevaluated values.

Microsoft.Build.Conversion

Contains types that Visual Studio uses to convert project files.

Microsoft.Build.Debugging

Contains types for managing the debugger.

Microsoft.Build.Evaluation

Contains types that the MSBuild object model uses to evaluate projects.

Microsoft.Build.Exceptions

Page 63: net notes

Contains exception types used by the MSBuild engine.

Microsoft.Build.Execution

Contains types that the MSBuild object model uses to build projects.

Microsoft.Build.Framework

Contains classes that make up the tasks, loggers, and events of MSBuild.

Microsoft.Build.Framework.XamlTypes

Contains classes used to represent XAML types parsed from files, rules, and other sources.

Microsoft.Build.Logging

Contains types used for logging the progress of a build.

Microsoft.Build.Tasks

Contains the implementation of all tasks shipping with MSBuild.

Microsoft.Build.Tasks.Deployment.Bootstrapper

Contains classes used internally by MSBuild.

Microsoft.Build.Tasks.Deployment.ManifestUtilities

Contains classes used internally by MSBuild.

Microsoft.Build.Tasks.Hosting

Contains classes used internally by MSBuild.

Microsoft.Build.Tasks.Windows

Contains classes used internally by MSBuild.

Microsoft.Build.Tasks.Xaml

Contains types that process XAML.

Microsoft.Build.Utilities

Provides helper classes that you can use to create your own MSBuild loggers and tasks.

Microsoft.CSharp

Contains classes that support compilation and code generation using the C# language.

Microsoft.CSharp.RuntimeBinder

Contains types that support interoperation between the dynamic language runtime (DLR) and C#.

Microsoft.Data.Entity.Build.Tasks

Contains types that represent MSBuild tasks used by the ADO.NET Entity Data Model Designer.

Microsoft.JScript

Page 64: net notes

Contains classes that support compilation and code generation using the JScript language.

Microsoft.SqlServer.Server

Contains classes that are specific to the integration of the.NET Framework common language runtime (CLR) component into Microsoft SQL Server, and the SQL Server database engine process execution environment.

Microsoft.VisualBasic

Contains classes that support compilation and code generation using the Visual Basic language.

Microsoft.VisualBasic.Activities

Contains classes that provide Visual Basic expressions that can be bound to In and Out arguments, and Visual Basic expression settings.

Microsoft.VisualBasic.Activities.XamlIntegration

Provides a type converter and XAML serializer for Microsoft.VisualBasic.Activities.VisualBasicSettings.

Microsoft.VisualBasic.ApplicationServices

Contains types that support the Visual Basic Application Model and provide access to application information.

Microsoft.VisualBasic.Compatibility.VB6

Contains types used by tools for upgrading from Visual Basic 6.0 to Visual Basic .NET.

Microsoft.VisualBasic.CompilerServices

Contains internal-use only types that support the Visual Basic compiler.

Microsoft.VisualBasic.Devices

Contains types that support the My objects related to devices in Visual Basic.

Microsoft.VisualBasic.FileIO

Contains types that support the My file system object in Visual Basic.

Microsoft.VisualBasic.Logging

Contains types that support the My logging objects in Visual Basic and provides a simple log listener that directs logging output to file.

Microsoft.VisualBasic.MyServices

Contains types that support My in Visual Basic.

Microsoft.VisualBasic.MyServices.Internal

Contains internal-use only types that support My in Visual Basic.

Microsoft.VisualC

Contains types that support the Visual C++ compiler.  

Microsoft.VisualC.StlClr

Contains types that implement the STL/CLR Library.

Page 65: net notes

Microsoft.VisualC.StlClr.Generic

Contains types that implement the generic interface to the STL/CLR Library.

Microsoft.Win32

Provides two types of classes: those that handle events raised by the operating system and those that manipulate the system registry.

Microsoft.Win32.SafeHandles

Contains classes that are abstract derivations of safe handle classes that provide common functionality supporting file and operating system handles.

Microsoft.Windows.Themes

Provides exposure to the set of themes defined by Windows Presentation Foundation (WPF).

System

Contains fundamental classes and base classes that define commonly used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. Other classes provide services supporting data type conversion, method parameter manipulation, mathematics, remote and local program invocation, application environment management, and supervision of managed and unmanaged applications.

System.Activities

Contains all the classes necessary to create and work with activities. The classes in this namespace enable you to define activities, the data flow into and out of activities, and variables.

System.Activities.Core.Presentation

Contains helper classes used in the default and extensibility scenarios for Windows Workflow Foundation.

System.Activities.Core.Presentation.Factories

Provides factories for creating activities that interact with collections and enable control flow in Windows Workflow Foundation.

System.Activities.Core.Presentation.Themes

Contains a class that is a collection of style configuration values used by the activity designers.

System.Activities.Debugger

Contains classes that provide support for debugging workflows.

System.Activities.DurableInstancing

Contains the SqlWorkflowInstanceStore class, which provides durability to workflow instances, and its helper classes.

System.Activities.ExpressionParser

Contains classes that support the compilation of expressions.

System.Activities.Expressions

Contains classes and expression activities that support the use of expressions in a workflow.

System.Activities.Hosting

Page 66: net notes

Contains classes that provide the base support for hosting and executing a workflow.

System.Activities.Persistence

Contains classes for capturing an object’s state independent of process or machine information.

System.Activities.Presentation

Contains base activity designer classes used to create custom activity designers.

System.Activities.Presentation.Converters

Provides converts for arguments, UI property data, and items in the editing model of the Windows Workflow Foundation.

System.Activities.Presentation.Debug

Contains classes that provide breakpoint management for a debugging process.

System.Activities.Presentation.Hosting

Contains classes that enable the host to interact with assemblies, commands, and imported namespaces.

System.Activities.Presentation.Metadata

Contains classes that enable you to work with custom attributes of elements.

System.Activities.Presentation.Model

Contains classes that enable you to work with items in the model tree of the designer, such as accessing the model items properties and attached properties. Also provides functionality to manage the model tree.

System.Activities.Presentation.PropertyEditing

Contains classes that enable updating properties by providing property editors, category editors, and access to properties, property values, and filters.

System.Activities.Presentation.Services

Provides classes that enable interacting with the model tree to perform tasks such as creating and locating model items, and mapping view items with model items.

System.Activities.Presentation.Toolbox

Provides support for classifying and using tools when rehosting outside of Visual Studio 2010.

System.Activities.Presentation.Validation

Contains classes that provide activity validation functionality for activities.

System.Activities.Presentation.View

Provides functionality related to the view elements in the workflow designer, including accessing and creating view elements, accessing commands, working with the view state, selections, and the expression textbox.

System.Activities.Statements

Contains activities that can be used to create workflows, for flow control, interacting with collections and variables, exceptions, compensation, transactions, and interacting with legacy workflows.

System.Activities.Tracking

Page 67: net notes

Contains classes used to create and interact with workflow tracking records.

System.Activities.Validation

Contains classes used for custom activity validation.

System.Activities.XamlIntegration

Contains classes that provide support for the serialization of activities into XAML.

System.AddIn

Contains an attribute for identifying add-ins.

System.AddIn.Contract

Contains types that provide the basis for communication between components that are updated independently.

System.AddIn.Contract.Automation

Contains types that components use to access type information and invoke type members.

System.AddIn.Contract.Collections

Contains types used to implement collection classes for add-in development.

System.AddIn.Hosting

Provides types for discovering, registering, activating, and controlling add-ins.

System.AddIn.Pipeline

Provides classes for constructing the communication pipeline between a host application and an add-in.

System.CodeDom

Contains classes that can be used to represent the elements and structure of a source code document. These elements can be used to model the structure of a source code document that can be output as source code in a supported language using the functionality provided by the System.CodeDom.Compiler namespace.

System.CodeDom.Compiler

Contains types for managing the generation and compilation of source code in supported programming languages. Code generators can each produce source code in a particular programming language based on the structure of Code Document Object Model (CodeDOM) source code models consisting of elements provided by the System.CodeDom namespace.

System.Collections

Contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.

System.Collections.Concurrent

Contains interfaces and classes that define various collection objects for concurrent processing.

System.Collections.Generic

Contains interfaces and classes that define generic collections, which enable users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

Page 68: net notes

System.Collections.ObjectModel

Contains classes that can be used as collections in the object model of a reusable library. Use these classes when properties or methods return collections.

System.Collections.Specialized

Contains specialized and strongly typed collections; for example, a linked list dictionary, a bit vector, and collections that contain only strings.

System.ComponentModel

Provides classes that are used to implement the run-time and design-time behavior of components and controls. This namespace includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components.

System.ComponentModel.Composition

Provides classes that constitute the majority of the Managed Extensibility Framework (MEF).

System.ComponentModel.Composition.Hosting

Provides classes for MEF that are useful to developers of extensible applications, or hosts.

System.ComponentModel.Composition.Primitives

Provides the primitive types underlying the MEF programming model.

System.ComponentModel.Composition.ReflectionModel

Provides types for the Managed Extensibility Framework (MEF) that are useful to developers using a reflection-based programming model.

System.ComponentModel.DataAnnotations

Provides attribute classes that are used to define metadata for ASP.NET Dynamic Data controls.

System.ComponentModel.Design

Contains classes that developers can use to build custom design-time behavior for components and user interfaces for configuring components at design time. The design time environment provides systems that enable developers to arrange components and configure their properties.

System.ComponentModel.Design.Data

Contains classes for implementing design-time behavior of data-related components.

System.ComponentModel.Design.Serialization

Provides types that support customization and control of serialization at design time.

System.Configuration

Contains the types that provide the programming model for handling configuration data.

System.Configuration.Assemblies

Contains classes that are used to configure an assembly.

System.Configuration.Install

Page 69: net notes

Provides classes that enable you to write custom installers for your own components. The Installer class is the base class for all custom installers in the .NET Framework.

System.Configuration.Provider

Contains the base classes shared by both server and client applications to support a pluggable model to easily add or remove functionality.

System.Data

Contains classes that constitute most of the ADO.NET architecture. The ADO.NET architecture enables you to build components that efficiently manage data from multiple data sources.

System.Data.Common

Contains classes shared by the .NET Framework data providers. A .NET Framework data provider describes a collection of classes used to access a data source, such as a database, in the managed space.

System.Data.Common.CommandTrees

Provides classes to build expressions that make up a command tree.

System.Data.Design

Contains classes that can be used to generate a custom typed dataset.

System.Data.Entity.Design

Contains classes to generate Entity Data Model (EDM) files and object source code.

System.Data.Entity.Design.AspNet

Contains the Entity Data Model (EDM) build providers for the ASP.NET build environment.

System.Data.Entity.Design.PluralizationServices

Provides types for changing words from singular to plural form, and vice versa.

System.Data.EntityClient

Contains the .NET Framework Data Provider for the Entity Framework.

System.Data.Linq

Contains classes that support interaction with relational databases in LINQ to SQL applications.

System.Data.Linq.Mapping

Contains classes that are used to generate a LINQ to SQL object model that represents the structure and content of a relational database.

System.Data.Mapping

Provides types for storing data mapping information.

System.Data.Metadata.Edm

Contains a set of types that represent concepts throughout the models used by the Entity Framework and a set of classes that help applications work with metadata.

System.Data.Objects

Page 70: net notes

Includes classes that provide access to the core functionality of Object Services.

System.Data.Objects.DataClasses

Includes classes that are base classes for types that are defined in an Entity Data Model (EDM), base classes for the types that are returned by navigation properties, and classes that define attributes that map common language runtime (CLR) objects to types in the conceptual model.

System.Data.Objects.SqlClient

Provides a type that contains common language runtime (CLR) methods that translate to database functions.

System.Data.Odbc

Contains classes that encapsulate the .NET Framework Data Provider for ODBC, which describes a collection of classes used to access an ODBC data source in the managed space.

System.Data.OleDb

Contains classes that encapsulate the .NET Framework Data Provider for OLE DB, which describes a collection of classes used to access an OLE DB data source in the managed space.

System.Data.OracleClient

Contains classes that encapsulate the .NET Framework Data Provider for Oracle, which describes a collection of classes used to access an Oracle data source in the managed space.

System.Data.Services

Provides access to classes used to build WCF Data Services.

System.Data.Services.BuildProvider

Contains classes that generate C# or Visual Basic code for a WCF Data Services client application based on the metadata returned by the data service.

System.Data.Services.Client

Represents the .NET Framework Client library that applications can use to interact with WCF Data Services.

System.Data.Services.Common

Contains a class that denotes the key property or properties of an entity.

System.Data.Services.Providers

Provides a series of interfaces that are implemented to define a custom data service provider for WCF Data Services.

System.Data.Sql

Contains classes that support SQL Server-specific functionality. The API extensions in this class add to the .NET Framework Data Provider for SQL Server (System.Data.SqlClient).

System.Data.SqlClient

Contains classes that encapsulate the .NET Framework Data Provider for SQL Server. The .NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space.

System.Data.SqlTypes

Page 71: net notes

Contains classes for native data types within SQL Server. These classes provide a faster alternative to other data types. Using the classes in this namespace helps prevent type conversion errors caused in situations where loss of precision could occur. Because other data types are converted to and from SqlTypes behind the scenes, explicitly creating and using objects within this namespace results in faster code as well.

System.Deployment.Application

Provides types to create custom upgrade behavior in ClickOnce applications.

System.Device.Location

Contains classes that provide a single API to encapsulate the multiple location providers on a computer and support seamless prioritization and transitioning between them. An application developer who uses this API does not need to know which location-sensing technologies are available on a particular computer and is freed from the burden of tailoring an application to a specific hardware configuration

System.Diagnostics

Provides classes that enable you to interact with system processes, event logs, and performance counters. This namespace also provides classes that let you debug your application and trace the execution of your code.

System.Diagnostics.CodeAnalysis

Contains classes for interaction with code analysis tools. Code analysis tools are used to analyze code for conformance to coding conventions such as naming or security rules.

System.Diagnostics.Contracts

Contains static classes for representing program constructs such as preconditions, postconditions, and invariants.

System.Diagnostics.Contracts.Internal

Provides classes that the binary rewriter can use to handle a contract failure.

System.Diagnostics.Design

Contains classes that can be used to extend design-time support for application monitoring and instrumentation.

System.Diagnostics.Eventing

Contains types to support implementation of an application on Windows Vista. The instrumentation, when enabled, logs event data to the Event Tracing for Windows (ETW) tracing subsystem.

System.Diagnostics.Eventing.Reader

Contains types to support reading from and managing event logs.

System.Diagnostics.PerformanceData

Contains classes that are used to provide counter data, which expose performance metrics to consumers.

System.Diagnostics.SymbolStore

Provides classes that enable you to read and write debug symbol information, such as source line to Microsoft intermediate language (MSIL) maps. Compilers targeting the .NET Framework can store the debug symbol information into programmer's database (PDB) files. Debuggers and code profiler tools can read the debug symbol information at run time.

System.DirectoryServices

Provides easy access to Active Directory from managed code. The namespace contains two component classes, DirectoryEntry and DirectorySearcher, which use the Active Directory Services Interfaces (ADSI) technology. ADSI is

Page 72: net notes

the set of interfaces that Microsoft provides as a flexible tool for working with a variety of network providers. ADSI gives the administrator the ability to locate and manage resources on a network with relative ease, regardless of the network's size.

System.DirectoryServices.AccountManagement

Provides uniform access and manipulation of user, computer, and group security principals across multiple principal stores.

System.DirectoryServices.ActiveDirectory

Provides a high-level abstraction object model that builds around Active Directory directory service tasks. The Active Directory directory service concepts such as forest, domain, site, subnet, partition, and schema are part of the object model.

System.DirectoryServices.Protocols

Provides the methods defined in the Lightweight Directory Access Protocol (LDAP) version 3 and Directory Services Markup Language (DSML) version 2.0 standards.

System.Drawing

Provides access to GDI+ basic graphics functionality. More advanced functionality is provided in the System.Drawing.Drawing2D, System.Drawing.Imaging, and System.Drawing.Text namespaces.

System.Drawing.Design

Contains classes that extend design-time user interface (UI) logic and drawing. You can further extend this design-time functionality to create custom toolbox items, type-specific value editors that can edit and graphically represent values of their supported types, or type converters that can convert values between certain types. This namespace provides the basic frameworks for developing extensions to the design-time UI.

System.Drawing.Drawing2D

Provides advanced two-dimensional and vector graphics functionality. This namespace includes the gradient brushes, the Matrix class (used to define geometric transforms), and the GraphicsPath class.

System.Drawing.Imaging

Provides advanced GDI+ imaging functionality. Basic graphics functionality is provided by the System.Drawing namespace.

System.Drawing.Printing

Provides print-related services. Typically, you create a new instance of the PrintDocument class, set the properties that describe what to print, and call the Print method to actually print the document.

System.Drawing.Text

Provides advanced GDI+ typography functionality. Basic graphics functionality is provided by the System.Drawing namespace. The classes in this namespace enable users to create and use collections of fonts.

System.Dynamic

Provides classes and interfaces that support the dynamic language runtime (DLR).

System.EnterpriseServices

Provides an important infrastructure for enterprise applications. COM+ provides a services architecture for component programming models deployed in an enterprise environment. This namespace provides .NET Framework objects with access to COM+ services, making the .NET Framework objects more practical for enterprise applications.

Page 73: net notes

System.EnterpriseServices.CompensatingResourceManager

Provides classes that enable you to use a Compensating Resource Manager (CRM) in managed code. A CRM is a service provided by COM+ that enables you to include non-transactional objects in Microsoft Distributed Transaction Coordinator (DTC) transactions. Although CRMs do not provide the capabilities of a full resource manager, they do provide transactional atomicity (all-or-nothing behavior) and durability through the recovery log.

System.Globalization

Contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency, and numbers, and the sort order for strings. These classes are useful for writing globalized (internationalized) applications.

System.IdentityModel.Claims

Contains types that support the use of claims in the Extensible Identity Model.

System.IdentityModel.Policy

Contains types to build or use authorization policies in Windows Communication Foundation (WCF).

System.IdentityModel.Selectors

Contains the types that provide security tokens for outgoing SOAP messages and that authenticate security tokens in incoming SOAP messages.

System.IdentityModel.Tokens

Contains the types that are related to the predefined security tokens that ship with Windows Communication Foundation (WFC).

System.IO

Contains types that enable synchronous and asynchronous reading and writing on data streams and files.

System.IO.Compression

Contains classes that provide basic compression and decompression for streams.

System.IO.IsolatedStorage

Contains types that support the creation and use of isolated stores. With these stores, you can read and write data that less trusted code cannot access and help prevent the exposure of sensitive information that can be saved elsewhere on the file system. Data is stored in compartments that are isolated by the current user and by the assembly in which the code exists.

System.IO.Log

Contains types for implementing a custom diagnostic logging or transaction processing system.

System.IO.MemoryMappedFiles

Provides classes for using a memory-mapped file, which maps the contents of a file to an application's logical address space.

System.IO.Packaging

Contains types that support storage of multiple data objects in a single container.

System.IO.Pipes

Page 74: net notes

Contains types that provide a means for interprocess communication through anonymous and/or named pipes.

System.IO.Ports

Contains classes that control serial ports, providing a framework for synchronous and event-driven I/O, access to pin and break states, access to serial driver properties, and enumerations for specifying port characteristics.

System.Linq

Contains classes and interfaces that support queries that use Language-Integrated Query (LINQ).

System.Linq.Expressions

Contains types that enable language-level code expressions to be represented as objects in the form of expression trees.

System.Management

Provides access to a rich set of management information and management events about the system, devices, and applications instrumented to the Windows Management Instrumentation (WMI) infrastructure.

System.Management.Instrumentation

Provides the classes necessary for instrumenting applications for management and exposing their management information and events through WMI to potential consumers.

System.Media

Contains classes for playing sound files and accessing system sounds.

System.Messaging

Provides classes that enable you to connect to, monitor, and administer message queues on the network and send, receive, or peek messages.

System.Messaging.Design

Contains classes that can be used to extend design-time support for System.Messaging classes.

System.Net

Provides a simple programming interface for many of the protocols used on networks today. The WebRequest and WebResponse classes form the basis of what are called pluggable protocols, an implementation of network services that enables you to develop applications that use Internet resources without worrying about the specific details of the individual protocols.

System.Net.Cache

Defines the types and enumerations used to define cache policies for resources obtained using the WebRequest and HttpWebRequest classes.

System.Net.Configuration

Contains classes that applications use to programmatically access and update configuration settings for the System.Net namespaces.

System.Net.Mail

Contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery.

System.Net.Mime

Page 75: net notes

Contains types that are used to represent Multipurpose Internet Mail Exchange (MIME) headers. These types are used with the types in the System.Net.Mail namespace to specify Content-Type, Content-Disposition and Content-transfer-Encoding headers when sending e-mail using the SmtpClient class.

System.Net.NetworkInformation

Provides access to network traffic data, network address information, and notification of address changes for the local computer. The namespace also contains classes that implement the Ping utility. You can use Ping and related classes to check whether a computer is reachable across the network.

System.Net.PeerToPeer

Provides access to peer networking functionality.

System.Net.PeerToPeer.Collaboration

Provides types that enhance peer-to-peer networking functionality and provide capabilities for serverless managed collaboration sessions.

System.Net.Security

Provides network streams for secure communications between hosts.

System.Net.Sockets

Provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to help control access to the network.

System.Numerics

Contains types that complement the numeric primitives, such as Byte, Double, and Int32, that are defined by the .NET Framework.

System.Printing

Contains types to support printing.

System.Printing.IndexedProperties

Contains classes that provide access to the properties of print system objects without using reflection, and enable rapid copying of the property settings to another object of the same type.

System.Printing.Interop

Provides types to support interconversion of managed PrintTicket objects and unmanaged Graphics Device Interface (GDI) DEVMODE structures.

System.Reflection

Contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types.

System.Reflection.Emit

Contains classes that enable a compiler or tool to emit metadata and Microsoft intermediate language (MSIL) and optionally generate a PE file on disk. The primary clients of these classes are script engines and compilers.

System.Resources

Provides classes and interfaces that enable developers to create, store, and manage various culture-specific resources used in an application.

Page 76: net notes

System.Resources.Tools

Contains the StronglyTypedResourceBuilder class, which provides support for strongly typed resources. Beginning with the .NET Framework version 2.0, this compile-time feature encapsulates access to resources by creating classes that contain a set of static read-only (get) properties, thus making it easier to consume resources.

System.Runtime

Contains advanced types that support diverse namespaces such as System, the Runtime namespaces, and the Security namespaces.

System.Runtime.Caching

Contains types that let you implement output caching in applications that are built on the .NET Framework.

System.Runtime.Caching.Configuration

Contains configuration handler classes for the .NET Framework caching feature.

System.Runtime.Caching.Hosting

Contains types that support the .NET Framework hosting environments that use caching features.

System.Runtime.CompilerServices

Provides functionality for compiler writers who use managed code to specify attributes in metadata that affect the run-time behavior of the common language runtime. The classes in this namespace are for compiler writers use only.

System.Runtime.ConstrainedExecution

Defines a set of types that enumerate and define a contract for reliability between the author of some code and the developers who take a dependency on that code. The types are intended for use in constrained execution regions (CERs) only.

System.Runtime.DurableInstancing

Contains classes that are used by the Windows Communication Foundation (WCF) infrastructure to implement a persistence provider.

System.Runtime.ExceptionServices

Provides classes for advanced exception handling.

System.Runtime.Hosting

Contains advanced types that are used in application activation within application domains.

System.Runtime.InteropServices

Provides a wide variety of members that support COM interop and platform invoke services. If you are unfamiliar with these services, see Interoperating with Unmanaged Code.

System.Runtime.InteropServices.ComTypes

Contains methods that are definitions of COM functions for managed code. These functions replace the now-obsolete UCOM methods in the System.Runtime.InteropServices namespace.

System.Runtime.InteropServices.Expando

Contains the IExpando interface, which lets you modify an object by adding or removing its members.

Page 77: net notes

System.Runtime.Remoting

Provides classes and interfaces that enable developers to create and configure distributed applications.

System.Runtime.Remoting.Activation

Provides classes and objects that support server and client activation of remote objects.

System.Runtime.Remoting.Channels

Contains classes that support and handle channels and channel sinks, which are used as the transport medium when a client calls a method on a remote object.

System.Runtime.Remoting.Channels.Http

Contains channels that use the HTTP protocol to transport messages and objects to and from remote locations. By default, the HTTP channels encode objects and method calls in SOAP format for transmission, but other encoding and decoding formatter sinks can be specified in the configuration properties of a channel.

System.Runtime.Remoting.Channels.Ipc

Defines a communication channel for remoting that uses the Interprocess Communication (IPC) system of the Windows operating system. Because it does not use network communication, the IPC channel is much faster than the HTTP and TCP channels, but it can only be used for communication between application domains on the same physical computer.

System.Runtime.Remoting.Channels.Tcp

Contains channels that use the TCP protocol to transport messages and objects to and from remote locations. By default, the TCP channels encode objects and method calls in binary format for transmission, but other encoding and decoding formatter sinks can be specified in the configuration properties of a channel.

System.Runtime.Remoting.Contexts

Contains objects that define the contexts all objects reside within. A context is an ordered sequence of properties that defines an environment for the objects within it. Contexts are created during the activation process for objects that are configured to require certain automatic services such synchronization, transactions, just-in-time (JIT) activation, security, and so on. Multiple objects can live inside a context.

System.Runtime.Remoting.Lifetime

Contains classes that manage the lifetime of remote objects. Traditionally, distributed garbage collection uses reference counts and pinging for control over the lifetime of objects. This works well when there are a few clients per service, but does not scale well to thousands of clients per service. The remoting lifetime service associates a lease with each service, and deletes a service when its lease time expires. The lifetime service can take on the function of a traditional distributed garbage collector, and it also adjusts well when the numbers of clients per server increases.

System.Runtime.Remoting.Messaging

Contains classes used to create and remote messages. The remoting infrastructure uses messages to communicate with remote objects. Messages are used to transmit remote method calls, to activate remote objects, and to communicate information. A message object carries a set of named properties, including action identifiers, envoy information, and parameters.

System.Runtime.Remoting.Metadata

Contains classes and attributes that can be used to customize generation and processing of SOAP for objects and fields. The classes of this namespace can be used to indicate the SOAPAction, type output, XML element name, and the method XML namespace Uniform Resource Identifier (URI).

System.Runtime.Remoting.Metadata.W3cXsd2001

Page 78: net notes

Contains the XML Schema Definition (XSD) defined by the World Wide Web Consortium (W3C) in 2001. The XML Schema Part 2: Datatypes specification from W3C identifies format and behavior of various data types. This namespace contains wrapper classes for the data types that conform to the W3C specification. All date and time types conform to the ISO standards specification.

System.Runtime.Remoting.MetadataServices

Contains the classes used by the Soapsuds.exe command line tool and the user code to convert metadata to and from XML schema for the remoting infrastructure.

System.Runtime.Remoting.Proxies

Contains classes that control and provide functionality for proxies. A proxy is a local object that is an image of a remote object. Proxies enable clients to access objects across remoting boundaries.

System.Runtime.Remoting.Services

Contains service classes that provide functionality to the .NET Framework.

System.Runtime.Serialization

Contains classes that can be used for serializing and deserializing objects. Serialization is the process of converting an object or a graph of objects into a linear sequence of bytes for either storage or transmission to another location. Deserialization is the process of taking in stored information and recreating objects from it.

System.Runtime.Serialization.Configuration

Contains classes used to read the values found in application configuration files in the <system.xml.serialization> section.

System.Runtime.Serialization.Formatters

Provides common enumerations, interfaces, and classes that are used by serialization formatters.

System.Runtime.Serialization.Formatters.Binary

Contains the BinaryFormatter class, which can be used to serialize and deserialize objects in binary format.

System.Runtime.Serialization.Formatters.Soap

Contains the SoapFormatter class, which can be used to serialize and deserialize objects in the SOAP format.

System.Runtime.Serialization.Json

Contains types for serializing objects to JavaScript Object Notation (JSON) and deserializing objects from JSON.

System.Runtime.Versioning

Contains advanced types that support versioning in side-by-side implementations of the .NET Framework.

System.Security

Provides the underlying structure of the .NET Framework security system, including base classes for permissions.

System.Security.AccessControl

Provides programming elements that control access to, and audit security-related actions on, securable objects.

System.Security.Authentication

Provides a set of enumerations that describe the security of a connection.

Page 79: net notes

System.Security.Authentication.ExtendedProtection

Provides support for authentication using extended protection for applications.

System.Security.Authentication.ExtendedProtection.Configuration

Provides support for configuration of authentication using extended protection for applications.

System.Security.Cryptography

Provides cryptographic services, including secure encoding and decoding of data, as well as many other operations, such as hashing, random number generation, and message authentication.

System.Security.Cryptography.Pkcs

Provides programming elements for Public Key Cryptography Standards (PKCS), including methods for signing data, exchanging keys, requesting certificates, public key encryption and decryption, and other security functions.

System.Security.Cryptography.X509Certificates

Contains the common language runtime implementation of the Authenticode X.509 v.3 certificate. This certificate is signed with a private key that uniquely and positively identifies the holder of the certificate.

System.Security.Cryptography.Xml

Contains classes to support the creation and validation of XML digital signatures.

System.Security.Permissions

Defines classes that control access to operations and resources based on policy.

System.Security.Policy

Contains code groups, membership conditions, and evidence. These three types of classes are used to create the rules applied by the .NET Framework security policy system. Evidence classes are the input to security policy, and membership conditions are the switches; together these create policy statements and determine the granted permission set. Policy levels and code groups are the structure of the policy hierarchy. Code groups are the encapsulation of a rule and are arranged hierarchically in a policy level.

System.Security.Principal

Defines a principal object that represents the security context under which code is running.

System.Security.RightsManagement

Contains classes to support rights management of application-created content, such as content stored in a Package or XpsDocument.

System.ServiceModel

Contains the types necessary to build Windows Communication Foundation (WCF) service and client applications that can be used to build widely distributed applications.

System.ServiceModel.Activation

Contains the types required to construct and modify the dynamic creation of service hosts in a managed hosting environment.

System.ServiceModel.Activation.Configuration

Contains classes that represent the configuration elements in the SMSvcHost.exe.config file.

Page 80: net notes

System.ServiceModel.Activities

Contains classes that enable you to send messages to and receive messages from workflows.

System.ServiceModel.Activities.Activation

Contains the WorkflowServiceHostFactory class that provides instances of WorkflowServiceHost in managed hosting environments where the host instance is created dynamically in response to incoming messages.

System.ServiceModel.Activities.Configuration

Contains classes that are used to configure workflow services. These classes allow you to apply service and endpoint behaviors and configure tracking.

System.ServiceModel.Activities.Description

Contains classes that enable you to control various behaviors related to workflow services.

System.ServiceModel.Activities.Presentation.Factories

Contains factories that create Receive/SendReply and Send/ReceiveReply activity pairs.

System.ServiceModel.Activities.Tracking

Contains classes used to create tracking records for a workflow service instance. Tracking records are created by the workflow runtime during the execution of a workflow instance, and are sent to registered tracking participants.

System.ServiceModel.Activities.Tracking.Configuration

Contains classes used to configure workflow tracking. These classes enable you to specify the tracking information you want your workflow to generate.

System.ServiceModel.Channels

Contains the types required to construct and modify the messages used by clients and services to communicate with each other, the types of channels used to exchange messages, the channel factories and channel listeners used to construct those channels, and the binding elements used to configure them.

System.ServiceModel.ComIntegration

Contains the types necessary to integrate Windows Communication Foundation (WCF) service and client applications with COM components.

System.ServiceModel.Configuration

Contains types used by the Windows Communication Foundation (WCF) infrastructure to convert XML into Common Language Runtime (CLR) types.

System.ServiceModel.Description

Contains the types requires to construct and modify descriptions of services, contract, and endpoints that are used to build service runtimes and to export metadata.

System.ServiceModel.Diagnostics

Contains an enumeration that is used to configure performance counters for diagnostic purposes.

System.ServiceModel.Discovery

Contains the types required for the creation and use of discoverable services.

Page 81: net notes

System.ServiceModel.Discovery.Configuration

Contains classes that enable you to configure discovery settings in a configuration file.

System.ServiceModel.Discovery.Version11

Contains the classes required to create and use discoverable services. These classes implement the WS-Discovery version 1.1 protocol.

System.ServiceModel.Discovery.VersionApril2005

Contains the classes required to create and use discoverable services. These classes implement the April 2005 version of the WS-Discovery protocol.

System.ServiceModel.Discovery.VersionCD1

Contains the classes required to create and use discoverable services. These classes implement the Committee Draft 1 version of the WS-Discovery protocol.

System.ServiceModel.Dispatcher

Contains the types necessary to modify the run-time execution behavior of service and client applications.

System.ServiceModel.MsmqIntegration

Contains classes for Microsoft Message Queuing Service (MSMQ) integration, which enables communication between MSMQ applications and Windows Communication Foundation (WCF) applications.

System.ServiceModel.PeerResolvers

Contains classes that enable developers to customize and extend the Peer Name Resolution Protocol (PNRP) service.

System.ServiceModel.Persistence

Contains classes that allow workflow services (WCF services implemented as workflows) to be persisted into the persistence store.

System.ServiceModel.Routing

Contains classes that are used by the Windows Communication Foundation (WCF) infrastructure to implement the routing of messages between WCF endpoints.

System.ServiceModel.Routing.Configuration

Contains configuration classes that are used by the Windows Communication Foundation (WCF) infrastructure to convert XML into common language runtime (CLR) types.

System.ServiceModel.Security

Contains classes that support general Windows Communication Foundation (WCF) security.

System.ServiceModel.Security.Tokens

Contains types that represent security tokens and certificates for Windows Communication Foundation (WCF) security.

System.ServiceModel.ServiceMoniker40

System.ServiceModel.Syndication

Contains the types that make up the syndication object model.

Page 82: net notes

System.ServiceModel.Web

Contains types that make up the Web HTTP programming model.

System.ServiceModel.XamlIntegration

Provides utility classes to enable the serialization of entities to XAML.

System.ServiceProcess

Provides classes that enable you to implement, install, and control Windows service applications. Services are long-running executables that run without a user interface. Implementing a service involves inheriting from the ServiceBase class and defining specific behavior to process when start, stop, pause, and continue commands are passed in, as well as custom behavior and actions to take when the system shuts down.

System.ServiceProcess.Design

Contains classes that can be used to extend design-time support for Windows service applications.

System.Speech.AudioFormat

System.Speech.Recognition

Contains Windows Desktop Speech technology types for implementing speech recognition.

System.Speech.Recognition.SrgsGrammar

System.Speech.Synthesis

System.Speech.Synthesis.TtsEngine

Contains types that support the creation of custom engines based on the Speech Synthesis Markup Language (SSML) for rendering Text-to-Speech (TTS).

System.Text

Contains classes representing ASCII, Unicode, UTF-7, and UTF-8 character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String.

System.Text.RegularExpressions

Contains classes that provide access to the .NET Framework regular expression engine. The namespace provides regular expression functionality that can be used from any platform or language that runs within the.NET Framework.

System.Threading

Provides classes and interfaces that enable multithreaded programming. In addition to classes for synchronizing thread activities and access to data (Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class that lets you use a pool of system-supplied threads, and a Timer class that executes callback methods on thread pool threads.

System.Threading.Tasks

Provides types that simplify the work of writing concurrent and asynchronous code.

System.Timers

Provides the Timer component, which enables you to raise an event on a specified interval.

System.Transactions

Page 83: net notes

Contains classes that enable your code to participate in transactions. The classes support transactions with multiple, distributed participants, multiple phase notifications, and durable enlistments.

System.Transactions.Configuration

Contains classes that describe configuration options used by System.Transactions classes.

System.Web

Provides classes and interfaces that enable browser-server communication. This namespace includes the HttpRequest class, which provides extensive information about the current HTTP request, the HttpResponse class, which manages HTTP output to the client, and the HttpServerUtility class, which provides access to server-side utilities and processes. System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control.

System.Web.ApplicationServices

Provides classes that provide access to ASP.NET forms authentication, roles, and profiles application services as Windows Communication Foundation (WCF) services.

System.Web.Caching

Provides classes for caching frequently used data on the server. This includes the Cache class, a dictionary that lets you store arbitrary data objects, such as hash tables and data sets. It also provides expiration functionality for those objects, and methods that let you add and remove the objects. You can also add the objects with a dependency upon other files or cache entries, and perform a callback to notify your application when an object is removed from the cache.

System.Web.ClientServices

Contains classes that support access to the ASP.NET login, roles, and profiles services from Windows-based applications.

System.Web.ClientServices.Providers

Contains client service providers and other classes that support access to the ASP.NET login, roles, and profiles services from Windows-based applications.

System.Web.Compilation

Contains classes for generating and compiling custom file types within the ASP.NET build environment.

System.Web.Configuration

Contains classes that are used to set up ASP.NET configuration.

System.Web.DynamicData

Contains classes that provide the core functionality for ASP.NET dynamic data and extensibility features that let you customize dynamic data behavior.

System.Web.DynamicData.Design

Contains classes that provide design-time support for the classes in the System.Web.DynamicData namespace.

System.Web.DynamicData.ModelProviders

Contains classes that define the core functionality for ASP.NET Dynamic Data providers.

System.Web.Handlers

Contains HTTP handler classes that process HTTP requests to a Web server.

Page 84: net notes

System.Web.Hosting

Provides the functionality for hosting ASP.NET applications from managed applications outside of Microsoft Internet Information Services (IIS).

System.Web.Management

Contains classes and interfaces for managing and monitoring the health of Web applications.

System.Web.Mobile

Contains the core capabilities, including authentication and error-handling, required for building ASP.NET mobile Web applications.

System.Web.Profile

Contains classes that are used to implement the ASP.NET user profile in Web server applications.

System.Web.Query.Dynamic

Contains classes that are used to parse expressions from a LinqDataSource control into a Language-Integrated Query (LINQ).

System.Web.RegularExpressions

Provides regular expressions used to parse ASP.NET files. All members of the System.Web.RegularExpressions namespace are descendants of the Regex class.

System.Web.Routing

Provides classes that are used with URL routing, which enables you to use URLs that do not map to a physical file.

System.Web.Script

Contains classes that provide script resource information.

System.Web.Script.Serialization

Contains classes that provide JavaScript Object Notation (JSON) serialization and deserialization for managed types. It also provides extensibility features to customize serialization behavior.

System.Web.Script.Services

Provides attributes to customize Web service support for using AJAX functionality in ASP.NET.

System.Web.Security

Contains classes that are used to implement ASP.NET security in Web server applications.

System.Web.Services

Consists of the classes that enable you to create XML Web services using ASP.NET and XML Web service clients. XML Web services are applications that provide the ability to exchange messages in a loosely coupled environment using standard protocols such as HTTP, XML, XSD, SOAP, and WSDL. XML Web services enable the building of modular applications within and across companies in heterogeneous environments, making them interoperable with a broad variety of implementations, platforms, and devices.

System.Web.Services.Configuration

Consists of the classes that configure how XML Web services created using ASP.NET run.

Page 85: net notes

System.Web.Services.Description

Consists of the classes that enable you to publicly describe an XML Web service by using the Web Services Description Language (WSDL). Each class in this namespace corresponds to a specific element in the WSDL specification, and the class hierarchy corresponds to the XML structure of a valid WSDL document.

System.Web.Services.Discovery

Consists of the classes that enable XML Web service clients to locate the available XML Web services on a Web server through a process called XML Web Services Discovery.

System.Web.Services.Protocols

Consists of the classes that define the protocols used to transmit data across the wire during the communication between XML Web service clients and XML Web services created using ASP.NET.

System.Web.SessionState

Supplies classes and interfaces that enable storage of data specific to a single client within a Web application on the server. The session state data is used to give the client the appearance of a persistent connection with the application. State information can be stored within local process memory or, for Web farm configurations, out-of-process using either the ASP.NET State service or a SQL Server database.

System.Web.UI

Provides classes and interfaces that enable you to create ASP.NET server controls and ASP.NET Web pages for the user interface of your ASP.NET Web applications. This namespace includes the Control class, which provides all HTML server controls, Web server controls, and user controls with a common set of functionality. It also includes the Page control, which is generated automatically whenever a request is made for an .aspx file in an ASP.NET Web application. Also included are classes which provide the server controls with data-binding functionality, the ability to save the view state of a given control or page, and parsing functionality.

System.Web.UI.Adapters

Contains the base classes for control adapters and page adapters, which you can use to override life-cycle states of pages and controls to modify their default markup or behavior for new markup standards or for specific browsers.

System.Web.UI.DataVisualization.Charting

Contains types for the Chart Web server control.

System.Web.UI.Design

Contains classes that can be used to extend design-time support for ASP.NET Web pages and for Web server controls.

System.Web.UI.Design.MobileControls

Obsolete. Contains classes that provide design-time support for the classes in the System.Web.UI.MobileControls namespace. The classes in this namespace are obsolete; use the classes in System.Web.UI.Design.WebControls instead.

System.Web.UI.Design.MobileControls.Converters

Contains classes that provide design-time support for data type converters in mobile controls.

System.Web.UI.Design.WebControls

Contains classes that can be used to extend design-time support for Web server controls.

System.Web.UI.Design.WebControls.WebParts

Page 86: net notes

Contains classes that provide design-time support for controls derived from classes in the System.Web.UI.WebControls.WebParts namespace.

System.Web.UI.HtmlControls

Consists of a collection of classes that enable you to create HTML server controls on a Web Forms page. HTML server controls run on the server and map directly to standard HTML tags supported by most browsers. This enables you to programmatically control the HTML elements on a Web Forms page.

System.Web.UI.MobileControls

Obsolete. Contains a set of ASP.NET server controls that can intelligently render your application for different mobile devices. The classes in this namespace are obsolete; use the controls in System.Web.UI.WebControls instead.

System.Web.UI.MobileControls.Adapters

Contains classes you can use to override life-cycle stages of a mobile control to modify its default HTML, CHTML, or WML markup or behavior for new markup standards or for specific browsers and mobile devices.

System.Web.UI.MobileControls.Adapters.XhtmlAdapters

Contains classes you can use to override life-cycle stages of a mobile control to modify its default XHTML markup or behavior for new markup standards or for specific browsers and mobile devices.

System.Web.UI.WebControls

Contains classes that enable you to create Web server controls on a Web page. Web server controls run on the server and include form controls such as buttons and text boxes. They also include special-purpose controls such as a calendar. Because Web server controls run on the server, you can programmatically control these elements. Web server controls are more abstract than HTML server controls. Their object model does not necessarily reflect HTML syntax.

System.Web.UI.WebControls.Adapters

Contains classes you can use to override life-cycle stages of a Web control to modify a control's default markup or behavior for new markup standards or for specific browsers.

System.Web.UI.WebControls.Expressions

Provides classes for filtering data in a Web page using the QueryExtender control.

System.Web.UI.WebControls.WebParts

Contains an integrated set of classes and interfaces for creating Web pages whose appearance and behavior can be modified (personalized) by end users. The user-defined settings for each page are saved for future browser sessions.

System.Web.Util

Contains classes that enable callback methods to be run under the scope of a transaction and that enable work to be posted to separate threads.

System.Windows

Provides several important Windows Presentation Foundation (WPF) base element classes, various classes that support the WPF property system and event logic, and other types that are more broadly consumed by the WPF core and framework.

System.Windows.Annotations

Contains types that support user-created annotations on content displayed in Windows Presentation Foundation (WPF) document viewing controls.

Page 87: net notes

System.Windows.Annotations.Storage

Contains classes that define the storage architecture and media to save and retrieve user-created annotations.

System.Windows.Automation

Contains classes that provide support for Windows Presentation Foundation (WPF) user interface automation clients.

System.Windows.Automation.Peers

Defines the AutomationPeer base class and a set of types derived from it that correspond to.NET Framework controls.

System.Windows.Automation.Provider

Contains types for creating UI Automation providers for Windows Presentation Foundation (WPF).

System.Windows.Automation.Text

Contains enumerations that specify text formatting and related behavior for Windows Presentation Foundation (WPF) UI automation.

System.Windows.Baml2006

Contains reader and writer classes that can consume XAML in BAML form.

System.Windows.Controls

Contains classes to create controls that enable a user to interact with an application.

System.Windows.Controls.Primitives

Contains base classes and controls that are intended to be used as part of other, more complex controls.

System.Windows.Converters

Contains classes that support type conversion during serialization in Windows Presentation Foundation (WPF).

System.Windows.Data

Contains classes used for binding properties to data sources, data source provider classes, and data-specific implementations of collections and views.

System.Windows.Documents

Contains classes that support FixedDocument, FlowDocument, and XML Paper Specification (XPS) document creation.

System.Windows.Documents.DocumentStructures

Contains classes that describe the structure of an XpsDocument in terms of sections, paragraphs, figures, bulleted or numbered lists, and tables.

System.Windows.Documents.Serialization

Contains classes that support the creation and use of run-time accessible plug-in serializers which read and write documents in different data formats.

System.Windows.Forms

Page 88: net notes

Contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Windows operating system.

System.Windows.Forms.DataVisualization.Charting

Contains types for the Chart Windows Forms control.

System.Windows.Forms.Design

Contains classes that support design-time configuration and behavior for Windows Forms components. These classes consist of: Designer classes that provide support for Windows Forms components, a set of design time services, UITypeEditor classes for configuring certain types of properties, and classes for importing ActiveX controls.

System.Windows.Forms.Design.Behavior

Contains classes for creating custom user interface behavior for components at design time.

System.Windows.Forms.Integration

Contains classes that support interoperation of Windows Forms and Windows Presentation Foundation (WPF) controls.

System.Windows.Forms.Layout

Contains classes that support design-time and run-time layout behaviors.

System.Windows.Forms.VisualStyles

Contains classes for rendering controls and other Windows user interface elements with visual styles.

System.Windows.Ink

Provides classes to interact with and manipulate ink on the Windows Presentation Foundation (WPF) platform.

System.Windows.Input

Contains classes that support the Windows Presentation Foundation (WPF) input system.

System.Windows.Input.Manipulations

Provides functionality for monitoring and responding to a collection of manipulators as a single composite, enabling an application to track the changes to the composite instead of the individual components.

System.Windows.Input.StylusPlugIns

Provides classes that support manipulating data from a tablet pen on the Windows Presentation Foundation (WPF) platform.

System.Windows.Interop

Contains classes that support interoperation between Windows Presentation Foundation (WPF) and other technologies.

System.Windows.Markup

Contains classes to support serialization and Extensible Application Markup Language (XAML) in Windows Presentation Foundation (WPF) applications.

System.Windows.Markup.Localizer

Contains types that assist in the localization of binary XAML (BAML) sources.

Page 89: net notes

System.Windows.Markup.Primitives

Contains classes that support Extensible Application Markup Language (XAML) in Windows Presentation Foundation (WPF) applications.

System.Windows.Media

Contains classes that enable integration of rich media, including drawings, text, and audio/video content, within Windows Presentation Foundation (WPF) applications.

System.Windows.Media.Animation

Contains classes that provide property animation functionality in Windows Presentation Foundation (WPF) applications.

System.Windows.Media.Converters

Contains types used by the MarkupWriter for serialization of Extensible Application Markup Language (XAML).

System.Windows.Media.Effects

Contains types that can be used to apply visual effects to bitmap images.

System.Windows.Media.Imaging

Contains types used to encode and decode bitmap images.

System.Windows.Media.Media3D

Contains types that support 3-D presentation in Windows Presentation Foundation (WPF) applications.

System.Windows.Media.Media3D.Converters

Defines types used by the MarkupWriter class for serialization of Extensible Markup Language (XAML).

System.Windows.Media.TextFormatting

Contains classes that control formatting of text, typically at a lower level than control-based text presentation or the text object model.

System.Windows.Navigation

Contains types used for navigation, including navigating between windows, and navigation journaling.

System.Windows.Resources

Contains low-level classes that support the Windows Presentation Foundation (WPF) resource model and the Resources build action.

System.Windows.Shapes

Contains a library of shapes that can be used in Extensible Application Markup Language (XAML) or code.

System.Windows.Shell

Contains types that provide managed code access to the enhanced functionality of the Windows 7 taskbar.

System.Windows.Threading

Contains classes that support the Windows Presentation Foundation (WPF) threading system.

Page 90: net notes

System.Windows.Xps

Contains classes that write XML Paper Specification (XPS) documents to a data store or print queue.

System.Windows.Xps.Packaging

Contains classes that enable applications to read and write the components of an XPS document.

System.Windows.Xps.Serialization

Contains classes that support serialization of XPS documents.

System.Workflow.Activities

Contains classes that define activities that can be added to workflows to create and run an executable representation of a work process.

System.Workflow.Activities.Configuration

Contains classes that represent sections of a configuration file.

System.Workflow.Activities.Rules

Contains classes that define the conditions and actions that form a rule.

System.Workflow.Activities.Rules.Design

Contains classes that manage the Rule Set Editor and the Rule Condition Editor dialog boxes.

System.Workflow.ComponentModel

Contains the types that are used to create activities and workflows.

System.Workflow.ComponentModel.Compiler

Provides the infrastructure for validating and compiling activities and workflows.

System.Workflow.ComponentModel.Design

Contains classes that developers can use to build custom design-time behavior for workflows and activities.

System.Workflow.ComponentModel.Serialization

Provides the infrastructure for managing the serialization of activities and workflows to and from Extensible Application Markup Language (XAML) and CodeDOM.

System.Workflow.Runtime

Contains types that can be used to control the workflow runtime engine and the execution of a workflow instance.

System.Workflow.Runtime.Configuration

Contains classes that are used to configure the workflow runtime engine.

System.Workflow.Runtime.DebugEngine

Contains types for use in debugging workflow instances.

System.Workflow.Runtime.Hosting

Page 91: net notes

Contains classes that are related to services provided to the workflow runtime engine by the host application.

System.Workflow.Runtime.Tracking

Contains types related to tracking services.

System.Xaml

Provides types that relate to XAML parsers and processors.

System.Xaml.Hosting

Contains classes related to XAML hosting.

System.Xaml.Hosting.Configuration

Contains classes related to XAML hosting configuration.

System.Xaml.Permissions

Contains types that specify permissions for certain XAML loading scenarios, such as loading under partial trust.

System.Xaml.Schema

Contains types that support the XAML type system for the XAML information set.

System.Xml

Provides standards-based support for processing XML.

System.Xml.Linq

Contains the types for LINQ to XML, which is an in-memory XML programming interface that enables you to modify XML documents efficiently and easily.

System.Xml.Resolvers

Provides support for prepopulating the cache with DTDs or XML streams.

System.Xml.Schema

Contains the XML classes that provide standards-based support for XML Schema definition language (XSD) schemas.

System.Xml.Serialization

Contains classes that are used to serialize objects into XML format documents or streams.

System.Xml.Serialization.Advanced

Contains classes that enable you to customize the code generated from a Web Services Description Language (WSDL) document.

System.Xml.Serialization.Configuration

Contains classes used to read the values found in application configuration files in the system.xml.serialization element section.

System.Xml.XPath

Page 92: net notes

Contains the classes that define a cursor model for navigating and editing XML information items as instances of the XQuery 1.0 and XPath 2.0 Data Model.

System.Xml.Xsl

Provides support for Extensible Stylesheet Transformation (XSLT) transforms. This namespace supports the W3C XSL Transformations (XSLT) Version 1.0 Recommendation.

System.Xml.Xsl.Runtime

Provides internal support for the classes in the System.Xml.Xsl namespace. The classes in this namespace support the .NET Framework infrastructure and are not intended to be used directly from your code.

UIAutomationClientsideProviders

Contains a single class that maps client automation providers.

Deprecated and Internal Namespaces

Minimal documentation is provided for the following namespaces, either because they have been deprecated or because they are for internal use only.

Microsoft.JScript.Vsa System.Configuration.Internal System.Data.Linq.SqlClient System.Data.Linq.SqlClient.Implementation System.Data.Services.Design System.Data.Services.Internal System.Deployment.Internal System.EnterpriseServices.Internal System.Runtime.InteropServices.CustomMarshalers System.ServiceModel.Internal System.Web.Configuration.Internal System.Web.Mail System.Windows.Forms.ComponentModel.Com2Interop System.Windows.Forms.PropertyGridInternal XamlGeneratedNamespace

C Sharp (programming language)From Wikipedia, the free encyclopedia

Jump to: navigation, search

The correct title of this article is C# (programming language). The substitution or omission of a # sign is because of technical restrictions.

C#

Page 93: net notes

Paradigm

multi-paradigm: structured,

imperative, object-oriented, event-

driven, functional, generic

Appeared in 2001

Designed by Microsoft

Developer Microsoft

Stable release 4.0 (April 12, 2010; 11 months ago)

Typing disciplinestatic, dynamic,[1] strong, safe,

nominative

Major

implementations.NET Framework, Mono, DotGNU

Dialects Cω, Spec#, Polyphonic C#

Influenced byJava,[2] C++,[3] Eiffel, Modula-3, Object

Pascal.[4]

Influenced D, F#, Java 5,[5] Nemerle, Vala

Platform Common Language Infrastructure

License CLR Proprietary

Usual file

extensions.cs

Website C# Language (MSDN)

C Sharp Programming at Wikibooks

C#[6] (pronounced /ˈsiː ˈʃɑrp/ see sharp) is a multi-paradigm programming language encompassing imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed by Microsoft within the .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270). C# is one of the programming languages designed for the Common Language Infrastructure.

C# is intended to be a simple, modern, general-purpose, object-oriented programming language.[7] Its development team is led by Anders Hejlsberg. The most recent version is C# 4.0, which was released on April 12, 2010.

Page 94: net notes

Contents[hide]

1 Design goals 2 Name 3 History

o 3.1 Versions 4 Features 5 Common Type System (CTS)

o 5.1 Categories of datatypes o 5.2 Boxing and unboxing

6 Preprocessor 7 Code comments 8 XML documentation system 9 Libraries 10 "Hello, world" example 11 Standardization and licensing 12 Implementations 13 See also 14 References 15 Further reading 16 External links

[edit] Design goals

The ECMA standard lists these design goals for C#:[7]

C# language is intended to be a simple, modern, general-purpose, object-oriented programming language. The language, and implementations thereof, should provide support for software engineering principles such as strong type

checking, array bounds checking, detection of attempts to use uninitialized variables, and automatic garbage collection. Software robustness, durability, and programmer productivity are important.

The language is intended for use in developing software components suitable for deployment in distributed environments. Source code portability is very important, as is programmer portability, especially for those programmers already familiar

with C and C++. Support for internationalization is very important. C# is intended to be suitable for writing applications for both hosted and embedded systems, ranging from the very large that

use sophisticated operating systems, down to the very small having dedicated functions. Although C# applications are intended to be economical with regard to memory and processing power requirements, the

language was not intended to compete directly on performance and size with C or assembly language.

[edit] Name

C-sharp musical note (left)

The name "C sharp" was inspired by musical notation where a sharp indicates that the written note should be made a semitone higher in pitch.[8] This is similar to the language name of C++, where "++" indicates that a variable should be incremented by 1.

Page 95: net notes

Due to technical limitations of display (standard fonts, browsers, etc.) and the fact that the sharp symbol (U+266F ♯ MUSIC

SHARP SIGN (HTML: &#9839;)) is not present on the standard keyboard, the number sign (U+0023 # NUMBER SIGN (HTML: &#35;)) was chosen to represent the sharp symbol in the written name of the programming language.[9] This convention is reflected in the ECMA-334 C# Language Specification.[7] However, when it is practical to do so (for example, in advertising or in box art[10]), Microsoft uses the intended musical symbol.

The "sharp" suffix has been used by a number of other .NET languages that are variants of existing languages, including J# (a .NET language also designed by Microsoft which is derived from Java 1.1), A# (from Ada), and the functional F#.[11] The original implementation of Eiffel for .NET was called Eiffel#,[12] a name since retired since the full Eiffel language is now supported. The suffix has also been used for libraries, such as Gtk# (a .NET wrapper for GTK+ and other GNOME libraries), Cocoa# (a wrapper for Cocoa) and Qt# (a .NET language binding for the Qt toolkit).

[edit] History

During the development of the .NET Framework, the class libraries were originally written using a managed code compiler system called Simple Managed C (SMC).[13][14][15] In January 1999, Anders Hejlsberg formed a team to build a new language at the time called Cool, which stood for "C-like Object Oriented Language".[16] Microsoft had considered keeping the name "Cool" as the final name of the language, but chose not to do so for trademark reasons. By the time the .NET project was publicly announced at the July 2000 Professional Developers Conference, the language had been renamed C#, and the class libraries and ASP.NET runtime had been ported to C#.

C#'s principal designer and lead architect at Microsoft is Anders Hejlsberg, who was previously involved with the design of Turbo Pascal, Embarcadero Delphi (formerly CodeGear Delphi and Borland Delphi), and Visual J++. In interviews and technical papers he has stated that flaws[citation needed] in most major programming languages (e.g. C++, Java, Delphi, and Smalltalk) drove the fundamentals of the Common Language Runtime (CLR), which, in turn, drove the design of the C# language itself.

James Gosling, who created the Java programming language in 1994, and Bill Joy, a co-founder of Sun Microsystems, the originator of Java, called C# an "imitation" of Java; Gosling further claimed that "[C# is] sort of Java with reliability, productivity and security deleted."[2][17] Klaus Kreft and Angelika Langer (authors of a C++ streams book) stated in a blog post that "Java and C# are almost identical programming languages. Boring repetition that lacks innovation," "Hardly anybody will claim that Java or C# are revolutionary programming languages that changed the way we write programs," and "C# borrowed a lot from Java - and vice versa. Now that C# supports boxing and unboxing, we'll have a very similar feature in Java." [18] Anders Hejlsberg has argued that C# is "not a Java clone" and is "much closer to C++" in its design.[19]

Since the release of C# 2.0 in November of 2005, the C# and Java languages have evolved on increasingly divergent trajectories, becoming somewhat less similar. One of the first major departures came with the addition of generics to both languages, with vastly different implementations. C# makes use of reification to provide "first-class" generic objects that can be used like any other class, with code generation performed at class-load time.[20] By contrast, Java's generics are essentially a language syntax feature, and they do not affect the generated byte code because the compiler performs type erasure on the generic type information after it has verified its correctness.[21]

Furthermore, C# has added several major features to accommodate functional-style programming, culminating in their LINQ extensions released with C# 3.0 and its supporting framework of Lambda Expressions, Extension Methods, and anonymous classes.[22] These features enable C# programmers to use functional programming techniques, such as closures, when it is advantageous to their application. The LINQ extensions and the functional imports help developers reduce the amount of "boilerplate" code that is included in common tasks like querying a database, parsing an xml file, or searching through a data structure, shifting the emphasis onto the actual program logic to help improve readability and maintainability.[23]

C# used to have a mascot called Andy (named after Anders Hejlsberg). It was retired on 29 Jan 2004.[24]

[edit] Versions

In the course of its development, the C# language has gone through several versions:

Page 96: net notes

VersionLanguage specification

Date .NET Framework Visual StudioECMA ISO/IEC Microsoft

C# 1.0December 2002 April 2003

January 2002 January 2002 .NET Framework 1.0 Visual Studio .NET 2002

C# 1.2 October 2003 April 2003 .NET Framework 1.1 Visual Studio .NET 2003

C# 2.0 June 2006 September 2006 September 2005 [note 1] November 2005 .NET Framework 2.0 Visual Studio 2005

C# 3.0None[note 2]

August 2007 November 2007 .NET Framework 3.5 Visual Studio 2008

C# 4.0 April 2010 April 2010 .NET Framework 4 Visual Studio 2010

1. ̂ The Microsoft C# 2.0 specification document only contains the new 2.0 features. For older features use the 1.2 specification above.

2. ̂ As of December 2010, there are no ECMA and ISO/IEC specifications for C# 3.0 and 4.0.

[edit] FeaturesSee also: C Sharp syntax

Note: The following description is based on the language standard and other documents listed in the external links section.

By design, C# is the programming language that most directly reflects the underlying Common Language Infrastructure (CLI). Most of its intrinsic types correspond to value-types implemented by the CLI framework. However, the language specification does not state the code generation requirements of the compiler: that is, it does not state that a C# compiler must target a Common Language Runtime, or generate Common Intermediate Language (CIL), or generate any other specific format. Theoretically, a C# compiler could generate machine code like traditional compilers of C++ or Fortran.

Summary of versions

C# 2.0 C# 3.0 C# 4.0 C# 5.0 (planned)

Featuresadded

Generics Partial types Anonymous methods Iterators Nullable types Private setters

(properties) Method group

conversions (delegates)

Implicitly typed local variables

Object and collection initializers

Auto-Implemented properties

Anonymous types Extension methods Query expressions Lambda expressions Expression trees

Dynamic binding Named and optional

arguments Generic co- and

contravariance

Asynchronous methods

Compiler as a service

Page 97: net notes

Some notable distinguishing features of C# are:

There are no global variables or functions. All methods and members must be declared within classes. Static members of public classes can substitute for global variables and functions.

Local variables cannot shadow variables of the enclosing block, unlike C and C++. Variable shadowing is often considered confusing by C++ texts.

C# supports a strict Boolean datatype, bool. Statements that take conditions, such as while and if, require an expression of a type that implements the true operator, such as the boolean type. While C++ also has a boolean type, it can be freely converted to and from integers, and expressions such as if(a) require only that a is convertible to bool, allowing a to be an int, or a pointer. C# disallows this "integer meaning true or false" approach on the grounds that forcing programmers to use expressions that return exactly bool can prevent certain types of common programming mistakes in C or C++ such as if (a = b) (use of assignment = instead of equality ==).

In C#, memory address pointers can only be used within blocks specifically marked as unsafe, and programs with unsafe code need appropriate permissions to run. Most object access is done through safe object references, which always either point to a "live" object or have the well-defined null value; it is impossible to obtain a reference to a "dead" object (one which has been garbage collected), or to a random block of memory. An unsafe pointer can point to an instance of a value-type, array, string, or a block of memory allocated on a stack. Code that is not marked as unsafe can still store and manipulate pointers through the System.IntPtr type, but it cannot dereference them.

Managed memory cannot be explicitly freed; instead, it is automatically garbage collected. Garbage collection addresses the problem of memory leaks by freeing the programmer of responsibility for releasing memory which is no longer needed.

In addition to the try...catch construct to handle exceptions, C# has a try...finally construct to guarantee execution of the code in the finally block.

Multiple inheritance is not supported, although a class can implement any number of interfaces. This was a design decision by the language's lead architect to avoid complication and simplify architectural requirements throughout CLI.

C# is more type safe than C++. The only implicit conversions by default are those which are considered safe, such as widening of integers. This is enforced at compile-time, during JIT, and, in some cases, at runtime. There are no implicit conversions between booleans and integers, nor between enumeration members and integers (except for literal 0, which can be implicitly converted to any enumerated type). Any user-defined conversion must be explicitly marked as explicit or implicit, unlike C++ copy constructors and conversion operators, which are both implicit by default. Starting with version 4.0, C# supports a "dynamic" data type that enforces type checking at runtime only.

Enumeration members are placed in their own scope. C# provides properties as syntactic sugar for a common pattern in which a pair of methods, accessor (getter) and mutator

(setter) encapsulate operations on a single attribute of a class. Full type reflection and discovery is available. C# currently (as of version 4.0) has 77 reserved words. Checked exceptions are not present in C# (in contrast to Java). This has been a conscious decision based on the issues of

scalability and versionability.[25]

[edit] Common Type System (CTS)

C# has a unified type system. This unified type system is called Common Type System (CTS).[26]

A unified type system implies that all types, including primitives such as integers, are subclasses of the System.Object class. For example, every type inherits a ToString() method. For performance reasons, primitive types (and value types in general) are internally allocated on the stack.

[edit] Categories of datatypes

CTS separates datatypes into two categories:[26]

1. Value types 2. Reference types

Value types are plain aggregations of data. Instances of value types do not have referential identity nor a referential comparison semantics - equality and inequality comparisons for value types compare the actual data values within the instances, unless the corresponding operators are overloaded. Value types are derived from System.ValueType, always

Page 98: net notes

have a default value, and can always be created and copied. Some other limitations on value types are that they cannot derive from each other (but can implement interfaces) and cannot have an explicit default (parameterless) constructor. Examples of value types are all primitive types, such as int (a signed 32-bit integer), float (a 32-bit IEEE floating-point number), char (a 16-bit Unicode code unit), and System.DateTime (identifies a specific point in time with nanosecond precision). Other examples are enum (enumerations) and struct (user defined structures).

In contrast, reference types have the notion of referential identity - each instance of a reference type is inherently distinct from every other instance, even if the data within both instances is the same. This is reflected in default equality and inequality comparisons for reference types, which test for referential rather than structural equality, unless the corresponding operators are overloaded (such as the case for System.String). In general, it is not always possible to create an instance of a reference type, nor to copy an existing instance, or perform a value comparison on two existing instances, though specific reference types can provide such services by exposing a public constructor or implementing a corresponding interface (such as ICloneable or IComparable). Examples of reference types are object (the ultimate base class for all other C# classes), System.String (a string of Unicode characters), and System.Array (a base class for all C# arrays).

Both type categories are extensible with user-defined types.

[edit] Boxing and unboxing

Boxing is the operation of converting a value of a value type into a value of a corresponding reference type.[26] Boxing in C# is implicit.

Unboxing is the operation of converting a value of a reference type (previously boxed) into a value of a value type.[26] Unboxing in C# requires an explicit type cast. A boxed object of type T can only be unboxed to a T (or a nullable T).[27]

Example:

int foo = 42; // Value type.

object bar = foo; // foo is boxed to bar.

int foo2 = (int)bar; // Unboxed back to value type.

[edit] Preprocessor

C# features "preprocessor directives"[28] (though it does not have an actual preprocessor) based on the C preprocessor that allow programmers to define symbols but not macros. Conditionals such as #if, #endif, and #else are also provided. Directives such as #region give hints to editors for code folding.

public class Foo

{

#region Procedures

public void IntBar(int firstParam) {}

public void StrBar(string firstParam) {}

public void BoolBar(bool firstParam) {}

#endregion

#region Constructors

public Foo() {}

Page 99: net notes

public Foo(int firstParam) {}

#endregion

}

[edit] Code comments

C# utilizes a double forward slash (//) to indicate the rest of the line is a comment. This is inherited from C++.

public class Foo

{

// a comment

public static void Bar(int firstParam) {} //Also a comment

}

Multi-line comments can be indicated by a starting forward slash/asterisk (/*) and ending asterisk/forward slash (*/). This is inherited from standard C.

public class Foo

{

/* A Multi-Line

comment */

public static void Bar(int firstParam) {}

}

[edit] XML documentation system

C#'s documentation system is similar to Java's Javadoc, but based on XML. Two methods of documentation are currently supported by the C# compiler.

Single-line documentation comments, such as those commonly found in Visual Studio generated code, are indicated on a line beginning with ///.

public class Foo

{

/// <summary>A summary of the method.</summary>

/// <param name="firstParam">A description of the parameter.</param>

/// <remarks>Remarks about the method.</remarks>

public static void Bar(int firstParam) {}

}

Multi-line documentation comments, while defined in the version 1.0 language specification, were not supported until the .NET 1.1 release.[29] These comments are designated by a starting forward slash/asterisk/asterisk (/**) and ending asterisk/forward slash (*/).[30]

public class Foo

Page 100: net notes

{

/** <summary>A summary of the method.</summary>

* <param name="firstParam">A description of the parameter.</param>

* <remarks>Remarks about the method.</remarks> */

public static void Bar(int firstParam) {}

}

Note there are some stringent criteria regarding white space and XML documentation when using the forward slash/asterisk/asterisk (/**) technique.

This code block:

/**

* <summary>

* A summary of the method.</summary>*/

produces a different XML comment from this code block:[30]

/**

* <summary>

A summary of the method.</summary>*/

Syntax for documentation comments and their XML markup is defined in a non-normative annex of the ECMA C# standard. The same standard also defines rules for processing of such comments, and their transformation to a plain XML document with precise rules for mapping of CLI identifiers to their related documentation elements. This allows any C# IDE or other development tool to find documentation for any symbol in the code in a certain well-defined way.

[edit] Libraries

The C# specification details a minimum set of types and class libraries that the compiler expects to have available. In practice, C# is most often used with some implementation of the Common Language Infrastructure (CLI), which is standardized as ECMA-335 Common Language Infrastructure (CLI).

[edit] "Hello, world" example

The following is a very simple C# program, a version of the classic "Hello, world" example:

using System;

class ExampleClass

{

static void Main()

{

Console.WriteLine("Hello, world!");

}

}

Page 101: net notes

The effect is to write the following text to the output console:

Hello, world!

Each line has a purpose:

using System;

The above line of code tells the compiler to use 'System' as a candidate prefix for types used in the source code. In this case, when the compiler sees use of the 'Console' type later in the source code, it tries to find a type named 'Console', first in the current assembly, followed by all referenced assemblies. In this case the compiler fails to find such a type, since the name of the type is actually 'System.Console'. The compiler then attempts to find a type named 'System.Console' by using the 'System' prefix from the using statement, and this time it succeeds. The using statement allows the programmer to state all candidate prefixes to use during compilation instead of always using full type names.

class ExampleClass

Above is a class definition. Everything between the following pair of braces describes ExampleClass.

static void Main()

This declares the class member method where the program begins execution. The .NET runtime calls the Main method. (Note: Main may also be called from elsewhere, like any other method, e.g. from another method of ExampleClass.) The static keyword makes the method accessible without an instance of ExampleClass. Each console application's Main entry point must be declared static. Otherwise, the program would require an instance, but any instance would require a program. To avoid that irresolvable circular dependency, C# compilers processing console applications (like that above) report an error if there is no static Main method. The void keyword declares that Main has no return value.

Console.WriteLine("Hello, world!");

This line writes the output. Console is a static class in the System namespace. It provides an interface to the standard input, output, and error streams for console applications. The program calls the Console method WriteLine, which displays on the console a line with the argument, the string "Hello, world!".

A GUI example:

using System.Windows.Forms;

class ExampleClass

{

static void Main()

{

MessageBox.Show("Hello, world!");

}

}

[edit] Standardization and licensing

In August, 2000, Microsoft Corporation, Hewlett-Packard and Intel Corporation co-sponsored the submission of specifications for C# as well as the Common Language Infrastructure (CLI) to the standards organization ECMA International. In December 2001, ECMA released ECMA-334 C# Language Specification. C# became an ISO standard in

Page 102: net notes

2003 (ISO/IEC 23270:2003 - Information technology — Programming languages — C#). ECMA had previously adopted equivalent specifications as the 2nd edition of C#, in December 2002.

In June 2005, ECMA approved edition 3 of the C# specification, and updated ECMA-334. Additions included partial classes, anonymous methods, nullable types, and generics (similar to C++ templates).

In July 2005, ECMA submitted the standards and related TRs to ISO/IEC JTC 1 via the latter's Fast-Track process. This process usually takes 6–9 months.

The C# language definition and the CLI are standardized under ISO and Ecma standards which provide reasonable and non-discriminatory licensing protection from patent claims. However, Microsoft uses C# and the CLI in its Base Class Library (BCL) which is the foundation of its proprietary .NET framework, and which provides a variety of non-standardized classes (extended I/O, GUI, web services, etc.). Some cases where Microsoft patents apply to standards used in the .NET framework are documented by Microsoft and the applicable patents are available on either RAND terms or through Microsoft's Open Specification Promise which releases patent rights to the public,[31] but there is some concern and debate as to whether there are additional aspects patented by Microsoft which are not covered, which may deter independent implementations of the full framework.

Microsoft has agreed not to sue open source developers for violating patents in non-profit projects for the part of the framework which is covered by the OSP.[32] Microsoft has also agreed not to enforce patents relating to Novell products against Novell's paying customers[33] with the exception of a list of products that do not explicitly mention C#, .NET or Novell's implementation of .NET (The Mono Project).[34] However, Novell maintains that Mono does not infringe any Microsoft patents.[35] Microsoft has also made a specific agreement not to enforce patent rights related to the Moonlight browser plugin, which depends on Mono, provided it is obtained through Novell.[36]

In a note posted on the Free Software Foundation's news website in June 2009, Richard Stallman warned that he believes that "Microsoft is probably planning to force all free C# implementations underground some day using software patents", and recommended that developers avoid taking what he described as the "gratuitous risk" associated with "depend[ing] on the free C# implementations".[37] The Free Software Foundation later reiterated its warnings,[38] claiming that the extension of Microsoft Community Promise to the C# and the CLI ECMA specifications[39] would not prevent Microsoft from harming open-source implementations of C#, because many specific Windows libraries included with .NET or Mono were not covered by this promise.

[edit] Implementations

The reference C# compiler is Microsoft Visual C#.

Other C# compilers exist, often including an implementation of the Common Language Infrastructure and the .NET class libraries up to .NET 2.0:

Microsoft's Rotor project (currently called Shared Source Common Language Infrastructure) (licensed for educational and research use only) provides a shared source implementation of the CLR runtime and a C# compiler, and a subset of the required Common Language Infrastructure framework libraries in the ECMA specification (up to C# 2.0, and supported on Windows XP only).

The Mono project provides an open source C# compiler, a complete open source implementation of the Common Language Infrastructure including the required framework libraries as they appear in the ECMA specification, and a nearly complete implementation of the Microsoft proprietary .NET class libraries up to .NET 3.5. As of Mono 2.6, there are no plans to implement WPF; WF is planned for a later release; and there are only partial implementations of LINQ to SQL and WCF.[40]

The DotGNU project also provides an open source C# compiler, a nearly complete implementation of the Common Language Infrastructure including the required framework libraries as they appear in the ECMA specification, and subset of some of the remaining Microsoft proprietary .NET class libraries up to .NET 2.0 (those not documented or included in the ECMA specification but included in Microsoft's standard .NET Framework distribution).

The DotNetAnywhere Micro Framework-like Common Language Runtime is targeted at embedded systems, and supports almost all C# 2.0 specifications. It is licensed under the MIT license conditions, is implemented in C and directed towards embedded devices.[41][42]

Page 103: net notes

[edit] See also

C# syntax Comparison of Java and C# Sing# Mono and Microsoft’s patents .NET Framework Standardization and licensing Oxygene Microsoft Visual Studio , IDE for C# SharpDevelop , an open-source C# IDE for Windows MonoDevelop , an open-source C# IDE for Linux, Windows and Mac OS X Morfik C#, a C# to JavaScript compiler complete with IDE and framework for Web application development. Borland Turbo C Sharp

[edit] References

1. ̂ Torgersen, Mads (October 27, 2008). "New features in C# 4.0". Microsoft. http://code.msdn.microsoft.com/csharpfuture/Release/ProjectReleases.aspx?ReleaseId=1686. Retrieved 2008-10-28.

2. ^ a b Wylie Wong (2002). "Why Microsoft's C# isn't". CNET: CBS Interactive. http://news.cnet.com/2008-1082-817522.html. Retrieved 2009-11-14.

3. ̂ Naugler, David (May 2007). "C# 2.0 for C++ and Java programmer: conference workshop". Journal of Computing Sciences in Colleges 22 (5). "Although C# has been strongly influenced by Java it has also been strongly influenced by C++ and is best viewed as a descendent of both C++ and Java.".

4. ̂ "The A-Z of Programming Languages: C#". Computerworld. 1 October 2008. http://www.computerworld.com.au/article/261958/a-z_programming_languages_c_/?pp=7. Retrieved 12 February 2010. "We all stand on the shoulders of giants here and every language builds on what went before it so we owe a lot to C, C++, Java, Delphi, all of these other things that came before us. (Anders Hejlsberg)"

5. ̂ Cornelius, Barry (December 1, 2005). "Java 5 catches up with C#". University of Oxford Computing Services. http://www.barrycornelius.com/papers/java5/onefile/. Retrieved June 18, 2009.

6. ̂ By convention, a hash sign is used for the second character in normal text; in artistic representations, sometimes a true sharp sign is used: C♯.

7. ^ a b c C# Language Specification (4th ed.). ECMA International. June 2006. http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf. Retrieved June 18, 2009.

8. ̂ Kovacs, James (September 7, 2007). "C#/.NET History Lesson". http://www.jameskovacs.com/blog/CNETHistoryLesson.aspx. Retrieved June 18, 2009.

9. ̂ "Microsoft C# FAQ". Microsoft. http://msdn.microsoft.com/vcsharp/previous/2002/FAQ/default.aspx. Retrieved 2008-03-25.[dead link] 10. ̂ "Visual C#.net Standard" (JPEG). Microsoft. September 4, 2003.

http://www.microsoft.com/presspass/images/gallery/boxshots/web/visual-c-sharp03.jpg. Retrieved June 18, 2009. 11. ̂ "F# FAQ". Microsoft Research. http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/faq.aspx. Retrieved June 18,

2009.[dead link] 12. ̂ Simon, Raphael; Stapf, Emmanuel; Meyer, Bertrand (June 2002). "Full Eiffel on the .NET Framework". Microsoft.

http://msdn.microsoft.com/en-us/library/ms973898.aspx. Retrieved June 18, 2009. 13. ̂ Zander, Jason (November 23, 2007). "Couple of Historical Facts". http://blogs.msdn.com/jasonz/archive/2007/11/23/couple-of-

historical-facts.aspx. Retrieved 2008-02-21. 14. ̂ "C# 3.0 New Features". http://www.learnitonweb.com/Articles/ReadArticle.aspx?contId=4&page=1. Retrieved 2008-06-08. 15. ̂ Guthrie, Scott (November 28, 2006). "What language was ASP.Net originally written in?".

http://aspadvice.com/blogs/rbirkby/archive/2006/11/28/What-language-was-ASP.Net-originally-written-in_3F00_.aspx. Retrieved 2008-02-21.

16. ̂ Hamilton, Naomi (October 1, 2008). "The A-Z of Programming Languages: C#". Computerworld. http://www.computerworld.com.au/article/261958/-z_programming_languages_c. Retrieved 2008-10-01.

17. ̂ Bill Joy (2002-02-07). "Microsoft's blind spot". cnet.com. http://news.cnet.com/2010-1071-831385.html. Retrieved 2010-01-12. 18. ̂ Klaus Kreft and Angelika Langer (2003-07-03). "After Java and C# - what is next?". artima.com.

http://www.artima.com/weblogs/viewpost.jsp?thread=6543. Retrieved 2010-01-12. 19. ̂ Osborn, John (2000-08-01), Deep Inside C#: An Interview with Microsoft Chief Architect Anders Hejlsberg, O'Reilly Media,

http://windowsdevcenter.com/pub/a/oreilly/windows/news/hejlsberg_0800.html, retrieved 2009-11-14 20. ̂ "Generics (C# Programming Guide)". Microsoft. http://msdn.microsoft.com/en-us/library/512aeb7t.aspx. Retrieved 2011-03-21. 21. ̂ Bracha, Gilad (2004-07-05). "Generics in the Java Programming Language". Sun Microsystems.

http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf. Retrieved 2011-03-21. 22. ̂ Don Box and Anders Hejlsberg (February 2007). "LINQ: .NET Language-Integrated Query". Microsoft.

http://msdn.microsoft.com/en-us/library/bb308959.aspx. Retrieved 2011-03-21. 23. ̂ Mercer, Ian (4/15/2010). "Why functional programming and LINQ is often better than procedural code". abodit.com.

http://blog.abodit.com/2010/04/why-functional-programming-is-better-linq-c-sharp-than-procedural-code/. Retrieved 2011-03-21.

Page 104: net notes

24. ̂ http://blogs.msdn.com/b/danielfe/archive/2004/01/29/64429.aspx 25. ̂ Venners, Bill; Eckel, Bruce (August 18, 2003). "The Trouble with Checked Exceptions". http://www.artima.com/intv/handcuffs.html.

Retrieved 2010-03-30. 26. ^ a b c d Archer, Tom (2001). "Part 2, Chapter 4: The Type System". Inside C#. Redmond, Washington: Microsoft Press. ISBN 0-7356-1288-9. 27. ̂ http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx 28. ̂ "C# Preprocessor Directives". C# Language Reference. Microsoft. http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx. Retrieved

June 18, 2009. 29. ̂ Horton, Anson (2006-09-11). "C# XML documentation comments FAQ".

http://blogs.msdn.com/ansonh/archive/2006/09/11/750056.aspx. Retrieved 2007-12-11. 30. ^ a b "Delimiters for Documentation Tags". C# Programmer's Reference. Microsoft. January 1, 1970 GMT. http://msdn.microsoft.com/en-

us/library/5fz4y783(VS.71).aspx. Retrieved June 18, 2009. 31. ̂ "Interoperability Principles". http://www.microsoft.com/interop/principles/default.mspx. 32. ̂ "Patent Pledge for Open Source Developers". http://www.microsoft.com/interop/principles/osspatentpledge.mspx. 33. ̂ "Patent Cooperation Agreement - Microsoft & Novell Interoperability Collaboration". Microsoft. November 2, 2006.

http://www.microsoft.com/interop/msnovellcollab/patent_agreement.mspx. Retrieved July 5, 2009. "Microsoft, on behalf of itself and its Subsidiaries (collectively “Microsoft”), hereby covenants not to sue Novell’s Customers and Novell’s Subsidiaries’ Customers for infringement under Covered Patents of Microsoft on account of such a Customer’s use of specific copies of a Covered Product as distributed by Novell or its Subsidiaries (collectively “Novell”) for which Novell has received Revenue (directly or indirectly) for such specific copies; provided the foregoing covenant is limited to use by such Customer (i) of such specific copies that are authorized by Novell in consideration for such Revenue, and (ii) within the scope authorized by Novell in consideration for such Revenue."

34. ̂ "Definitions". Microsoft. November 2, 2006. http://www.microsoft.com/interop/msnovellcollab/definitions2.aspx. Retrieved July 5, 2009.

35. ̂ Steinman, Justin (November 7, 2006). "Novell Answers Questions from the Community". http://www.novell.com/linux/microsoft/faq_opensource.html. Retrieved July 5, 2009. "We maintain that Mono does not infringe any Microsoft patents."

36. ̂ "Covenant to Downstream Recipients of Moonlight - Microsoft & Novell Interoperability Collaboration". Microsoft. September 28, 2007. http://www.microsoft.com/interop/msnovellcollab/moonlight.mspx. Retrieved March 8, 2008. "“Downstream Recipient” means an entity or individual that uses for its intended purpose a Moonlight Implementation obtained directly from Novell or through an Intermediate Recipient… Microsoft reserves the right to update (including discontinue) the foregoing covenant… “Moonlight Implementation” means only those specific portions of Moonlight 1.0 or Moonlight 1.1 that run only as a plug-in to a browser on a Personal Computer and are not licensed under GPLv3 or a Similar License."

37. ̂ Stallman, Richard (June 26, 2009). "Why free software shouldn't depend on Mono or C#". Free Software Foundation. http://www.fsf.org/news/dont-depend-on-mono. Retrieved July 2, 2009. "The danger is that Microsoft is probably planning to force all free C# implementations underground some day using software patents. ... We should systematically arrange to depend on the free C# implementations as little as possible. In other words, we should discourage people from writing programs in C#. Therefore, we should not include C# implementations in the default installation of GNU/Linux distributions, and we should distribute and recommend non-C# applications rather than comparable C# applications whenever possible."

38. ̂ "Microsoft's Empty Promise". Free Software Foundation. 2009-07-16. http://www.fsf.org/news/2009-07-mscp-mono. Retrieved 2009-078-03. "Until that happens, free software developers still should not write software that depends on Mono. C# implementations can still be attacked by Microsoft's patents: the Community Promise is designed to give the company several outs if it wants them. We don't want to see developers' hard work lost to the community if we lose the ability to use Mono, and until we eliminate software patents altogether, using another language is the best way to prevent that from happening."

39. ̂ "The ECMA C# and CLI Standards". 2009-07-06. http://port25.technet.com/archive/2009/07/06/the-ecma-c-and-cli-standards.aspx. Retrieved 2009-078-03.

40. ̂ http://www.mono-project.com/Compatibility 41. ̂ Dot Net Anywhere 42. ̂ Dot Net Anywhere license

[edit] Further reading

C# Language Pocket Reference. O' Reilly. 2002. ISBN 0-596-00429-X. Petzold, Charles (2002). Programming Microsoft Windows with C#. Microsoft Press. ISBN 0-7356-1370-2.

Generics sample in C#By Harikaran S | 5 Aug 2007 | Unedited contribution .NET2.0 VS2005 C#2.0 Windows Dev Intermediate

This article will explain about Generics feature in C# 2.0

Page 105: net notes

 

See Also

More like this More by this author

6

Article Browse Code Stats Revisions

  1.97 (25 votes)

1 2 3 4 5

Sponsored Links

Introduction

This article is going to deal with Generics feature in C# 2.0. Generics is a new feature added in C# 2.0 language and the Common Language Runtime (CLR). We can say it like Parametric Polymorphism. Generics allow us to create type safe collections with no boxing and unboxing overhead.

Background

As we know C# is a strongly typed language, programmers have to specify the type of an object at the time of writing the program.

"Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code."

We can write a generic method for sorting an array of objects, then invoke the generic method separately with an int array, a double array, a string array and so on, to sort each different type of array.

Generic methods enable us to specify, with a single method declaration, a set of related methods. Generic classes enable us to specify, with a single class declaration, a set of related classes. Similarly, generic interfaces enable us to specify, with a single interface declaration, a set of related interfaces. Generics provide compile-time type safety.

/w EPDw UKMjExO

Page 106: net notes

Using the code

I tried with our simple address book example in this article. Address class contains properties of DoorNo (int), StreetName (string), CityName (string), and PhoneNumber (int). In my implementation part, I may use all this properties to the object or some may be missed out:

Collapse | Copy Code

class Address

{

int _DoorNo;

public int DoorNo

{

get { return _DoorNo; }

set { _DoorNo = value; }

}

string _StreetName;

public string StreetName

{

get { return _StreetName; }

set { _StreetName = value; }

}

string _City;

public string City

{

get { return _City; }

set { _City = value; }

}

Page 107: net notes

string _State;

public string State

{

get { return _State; }

set { _State = value; }

}

int _Phone;

public int PhoneNo

{

get { return _Phone; }

set { _Phone = value; }

}

public Address() { }

public Address(int DoorNumber, string StreetName, string CityName)

{

this.DoorNo = DoorNumber;

this.StreetName = StreetName;

this.City = CityName;

this.PhoneNo = 0;

}

public Address(int DoorNumber, string StreetName, string CityName, int PhoneNumber)

Page 108: net notes

{

this.DoorNo = DoorNumber;

this.StreetName = StreetName;

this.City = CityName;

this.PhoneNo = PhoneNumber;

}

}

// Main class as follows:

class Program

{

static void Main(string[] args)

{

List<Address> myAddress = new List<Address>();

myAddress.Add(new Address(1,"New Street", "Chennai"));

myAddress.Add(new Address(2, "Second Main Road, TNHB", "Chennai", 866413553));

myAddress.Add(new Address(3, "New Street", "Bangalore"));

myAddress.Add(new Address(4, "Second Main Road, TNHB", "Bangalore", 885634367));

myAddress.Add(new Address(5, "New Street", "Pune"));

myAddress.Add(new Address(6, "Second Main Road, TNHB", "Pune", 433243664));

myAddress.Add(new Address(7, "New Street", "Gurgaon"));

myAddress.Add(new Address(8, "Second Main Road, TNHB", "Gurgaon", 564778634));

foreach (Address a in myAddress)

{

Console.WriteLine("New Address Entry follows: \n");

Console.WriteLine("Door Number : " + a.DoorNo);

Console.WriteLine("Street Name :" + a.StreetName);

Console.WriteLine("City :" + a.City);

Console.WriteLine("Phone Number:" + a.PhoneNo+"\n\n");

}

Console.ReadLine();

}

}

Introducing C# 2.0 Partial Types

By Edward Moemeka | 3 Oct 2005

C#Windows.NETDevIntermediate

A general discussion on C# 2.0 partial types.

Page 110: net notes

1 2 3 4 5

Sponsored Links

Top of Form

Introduction

Examine the example below:

Collapse | Copy Code

//definition for BinaryTree.h

class BinaryTree

{

public:

BinaryTree(void);

~BinaryTree(void);

int seed;

char* name;

void Load(char* name);

char* Find();

};

In C++, class definitions can be separated from the implementations. The above snippet is taken from a file BinaryTree.h which contains all the definitions associated with the BinaryTree class but no implementation code. Continuing with the example, the implementation file BinaryTree.cpp would be defined as follows:

Collapse | Copy Code

#include ".\binarytree.h"

BinaryTree::BinaryTree(void)

{

}

BinaryTree::~BinaryTree(void)

/w EPDw UKMjExO

Page 111: net notes

{

}

void BinaryTree::Load(char* str){

this->name = str;

}

char* BinaryTree::Find(){

return this->name;

}

As you can see from the sample, the first line of BinaryTree.cpp explicitly declares the inclusion of the class definition found in binarytree.h. Consequently, this completely separate file can use members defined in the latter as though they were defined there. The sample is, of course, nonsensical, but the concept nevertheless prevails; the ability to create types across multiple files.

It is important to note that the idea of having multiple public types in one file was so revolting to the devout object oriented programmer at one time that entire languages, Java for instance, excluded it. However, you will find that while it is good programming practice to maintain all source code for a type in a single file, sometimes a type becomes large enough that this is an impractical constraint.

Partials

C# 2.0 introduces the concept of partial type definitions for classes, structs, and interfaces, as a means to break types in a program into multiple pieces to be stored in different source files for easier maintenance and development. This approach is particularly useful when the need arises to use nested types or provide interface implementation.

Unlike C/C++, where a #include keyword was used to explicitly bind the contents of a header file to the implementation file, C# 2.0 partial type links are inferred through the type names given. Also, these are no interface definitions necessary in C# 2.0. A sample of a partial type is given below:.

Collapse | Copy Code

//Binarytree_header.cs

public partial class BinaryTree

{

int seed;

string name;

public BinaryTree()

{

}

}

Page 112: net notes

The above example attempts to recreate the BinaryTree sample we saw earlier in the chapter, using C#; notice that no include statements are needed, nor are any function prototypes defined. Further implementation of this class may now be defined in other files; for instance, a BinaryTree_Load.cs file may be created which produces more BinaryTree functionality.

Collapse | Copy Code

//BinaryTree_load.cs: Load functionality

public partial class BinaryTree

{

public void Load(string name)

{

this.name = name;

}

}

We can also create another file BinaryTree_find.cs which would have all the functionality associated with finding an element in the tree.

Collapse | Copy Code

//BinaryTree_find.cs: find functionality

public partial class BinaryTree

{

public string Find()

{

return name;

}

}

As you can see from the above samples, the new type modifier, partial, is used when defining a type in multiple parts. It indicates that additional parts may exist elsewhere. I stress the word may because each partial type declaration is autonomous. The example below illustrates this by creating a partial type declaration that includes no other parts:

Collapse | Copy Code

public partial class BinaryTree

{

int x;

}

The code above will compile successfully. Adding another part to the type will not change this successful compilation.

Page 113: net notes

Collapse | Copy Code

public partial class BinaryTree

{

int y;

}

Finally, a constructor can be added to instantiate the two variables defined in both parts of the type. A sample showing all three parts is highlighted below:

Collapse | Copy Code

public partial class BinaryTree

{

int x;

}

public partial class BinaryTree

{

int y;

}

public partial class BinaryTree

{

public BinaryTree()

{

this.x = 100;

this.y = 100;

}

}

Each partial type declaration must include the partial modifier, and must be declared within the same namespace as the other parts.

Compiling the code above will produce the following type definition:

Collapse | Copy Code

public partial class BinaryTree

{

Page 114: net notes

int x;

int y;

public BinaryTree()

{

this.x = 100;

this.y = 100;

}

}

If we compiled the BinaryTree sample from the first section, it would produce a type definition similar to the one depicted below:

Collapse | Copy Code

public class BinaryTree

{

int seed;

string name;

public BinaryTree()

{

}

public void Load(string name)

{

this.name = name;

}

public string Find()

{

return name;

}

}

It is important to note that partial types do not allow already compiled types to be extended. This is because all parts of a partial type must be compiled together such that the parts can be merged at compile-time to produce an actual type; as discussed in the example above. The partial modifier, if it appears, must appear immediately before either class, struct, or interface keywords, but is not itself a keyword.

Page 115: net notes

Nested Partials

Examine the three types defined in the sample below:

Collapse | Copy Code

public struct DataSource

{

public string connectionString;

}

public class DataAccessLayer

{

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

public class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

Page 116: net notes

public DataSource this[string dataSourceName]

{

get

{

return (DataSource )items[dataSourceName];

}

}

}

}

The snippet defines a struct DataSource of which the type DataSourceCollection is an aggregate through the items Hashtable. This type DataSourceCollection also happens to be a nested type of the DataAccessLayer type. Using partial types in this scenario, the nested type DataSourceCollection may also be declared in multiple parts by using the partial modifier. Hence DataAccessLayer may also be defined as follows:

Collapse | Copy Code

public class DataAccessLayer

{

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

public partial class DataSourceCollection

Page 117: net notes

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

}

public partial class DataSourceCollection

{

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

}

}

}

This would not make too much sense though; since the type DataSourceCollection is only qualified through its container DataAccessLayer, there is no way to specify a part outside of the DataSourceCollection type definition. A more optimal approach is to define either the containing type as partial with the contained type as not.

Collapse | Copy Code

public partial class DataAccessLayer

{

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

Page 118: net notes

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

}

public partial class DataAccessLayer

{

public class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

}

}

}

Or to define both containing and contained parts as partial:

Collapse | Copy Code

Page 119: net notes

public partial class DataAccessLayer

{

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

}

public partial class DataAccessLayer

{

public partial class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

}

}

public partial class DataAccessLayer

{ public partial class DataSourceCollection

Page 120: net notes

{

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

}

}

}

The first example shows an easy solution to defining nested types. With the power of partial classes, nested types can be completely isolated to their own files. The DataAccessLayer is defined as partial so that the nested type DataSourceCollection can be defined in a separate part. The second example is probably more of a telling of the dangers of partial types when used for no good reason. Here, we see that both the containing type DataAccessLayer and the contained type DataSourceCollection are defined as partial. Hence, the definitions can be broken into multiple parts. Please practice caution when using partial types, particularly with regard to nested types. You will find that in a complex program, it will be almost impossible to determine what the full definition of any one type is once it is defined as partial.

Partial Type Attributes

Attributes on partial types are combined in an unspecified order so that they appear to all be defined on the given type. In the preceding section, we defined a type DataAccessLayer as follows:

Collapse | Copy Code

public partial class DataAccessLayer

{

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

public DataSourceCollection DataSources

{

get

{

Page 121: net notes

return sources;

}

}

}

public partial class DataAccessLayer

{

public class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

}

}

}

Attributes can be added to each part of the type definition as follows:

Collapse | Copy Code

//Dal.cs

[Docking]

public partial class DataAccessLayer

{

DataSourceCollection sources;

Page 122: net notes

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

}

//dal.datasourcecollection.cs

[Serializable]

public partial class DataAccessLayer

{

public class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

Page 123: net notes

}

}

}

In the above example, a different attribute has been added to each part of the definition of DataAccessLayer. To the part defined in dal.cs, the attribute DockingAttribute has been attached. To the part defined in dal.datasourcecollection.cs, SerializableAttribute has been attached. This activity is equivalent to specifying both attributes on the type as follows:

Collapse | Copy Code

[Serializable, Docking ]

Inheritance and Interface Implementation

Now that we are done having all this fun, it's time to lay down some rules regarding what you can and can't do with partial types. To help with the discussion, it is important that we visualize what the end result of a partial type is. The previous section defined a partial type DataAccessLayer as follows:

Collapse | Copy Code

//Dal.cs

[Docking]

public partial class DataAccessLayer

{

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

}

Page 124: net notes

//dal.datasourcecollection.cs

[Serializable]

public partial class DataAccessLayer

{

public class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

}

}

}

This definition, once compiled, will be equivalent to the listing below:

Collapse | Copy Code

[Docking, Serializable]

public class DataAccessLayer

{

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

Page 125: net notes

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

public class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

}

}

}

The lesson here is that a partial class, no matter how fragmented, is still one functional unit. Hence, any accessibility specifications applied to a partial type must agree with all parts of the type that also include the accessibility specification. The concept is illustrated with the sample below:

Collapse | Copy Code

[Docking]

public partial class DataAccessLayer : GenericDAL

{

Page 126: net notes

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

}

internal partial class DataAccessLayer : GenericDAL

{

public class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

}

Page 127: net notes

}

}

Notice that in this definition of DataAccessLayer, the two parts inherit from a base type GenericDAL. Also notice that while one part defines the class as public, the other uses the internal modifier. Attempting to compile this listing will fail with the following message:

Collapse | Copy Code

Error 1: Partial declarations of 'PartialTypes2.DataAccessLayer'

have conflicting accessibility modifiers

The reason is evident from our first demonstration in this section. Although DataAccessLayer is fragmented, it is still a type, and a type cannot be both internal and public at the same time.

The next issue is that of base classes, and is not as easy to ascertain. Examine the listing below:

Collapse | Copy Code

[Docking]

public partial class DataAccessLayer : GenericDAL

{

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

}

partial class DataAccessLayer : DataSource

Page 128: net notes

{

public class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

}

}

}

Although the modifier incompatibility has been removed from the type, a problem persists during compilation of the above source. The difference here is that the second part of DataAccessLayer is now attempting to inherit from a different base type DataSource, than the first part which inherits from GenericDAL. This might not seem intuitive because it contradicts the combining behavior of partial type attributes; however, returning to our initial demonstration on the singularity of partial types, DataAccessLayer is a type; consequently, it can only inherit from one base class. The formal rule dictates that when a partial class declaration includes a base class specification, it must agree with all other parts that include a base class specification. Attempting to compile the listing above would produce the following error message:

Collapse | Copy Code

Error 1: Partial declarations of 'PartialTypes2.DataAccessLayer' must not specify different base classes

Now in the world of interfaces, where multiple inheritance is the game, the compiling behavior returns. Examine the example below.

Collapse | Copy Code

public partial class DataAccessLayer : GenericDAL

{

DataSourceCollection sources;

public DataAccessLayer()

{

Page 129: net notes

sources = new DataSourceCollection();

}

}

partial class DataAccessLayer : IDataSourceManager

{

public DataSourceCollection DataSources

{

get

{

return sources;

}

}

public class DataSourceCollection

{

Hashtable items;

public DataSourceCollection()

{

items = new Hashtable();

}

public DataSource this[string dataSourceName]

{

get

{

return (DataSource)items[dataSourceName];

}

}

}

}

Page 130: net notes

Similar to the example in the last section, the second part of DataAccessLayer defines a different base than the first. Unlike the sample in the previous section, however, IDataSourceManager is an interface and not a class. The formal rule states that the set of base interfaces for a type declared in multiple parts is the union of the base interfaces specified on each part. Furthermore, a particular base interface may only be named once on each part, but it is permitted for multiple parts to name the same base interface(s).

This means that the first part in the listing above could have been defined to include the IDataSourceManager interface as well. The listing below illustrates.

Collapse | Copy Code

public partial class DataAccessLayer : GenericDAL, IDataSourceManager

{

DataSourceCollection sources;

public DataAccessLayer()

{

sources = new DataSourceCollection();

}

}

Bottom of Form

http://msdn.microsoft.com/en-us/magazine/cc163970.aspx (link for iterators,anonymous

methods,partial types)

Boxing and Unboxing (C# Programming Guide)Visual Studio 2010

Other Versions

Updated: July 2010

Page 131: net notes

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system, in which a value of any type can be treated as an object.

In the following example, the integer variable i is boxed and assigned to object o.

VB

C#

C++

F#

JScript

Copy

int i = 123;

// The following line boxes i.

object o = i;

The object o can then be unboxed and assigned to integer variable i:

VB

C#

C++

F#

JScript

Page 132: net notes

Copy

o = 123;

i = (int)o; // unboxing

The following examples illustrate how boxing is used in C#.

VB

C#

C++

F#

JScript

Copy

// String.Concat example.

// String.Concat has many versions. Rest the mouse pointer on

// Concat in the following statement to verify that the version

// that is used here takes three object arguments. Both 42 and

// true must be boxed.

Console.WriteLine(String.Concat("Answer", 42, true));

Page 133: net notes

// List example.

// Create a list of objects to hold a heterogeneous collection

// of elements.

List<object> mixedList = new List<object>();

// Add a string element to the list.

mixedList.Add("First Group:");

// Add some integers to the list.

for (int j = 1; j < 5; j++)

{

// Rest the mouse pointer over j to verify that you are adding

// an int to a list of objects. Each element j is boxed when

// you add j to mixedList.

mixedList.Add(j);

}

// Add another string and more integers.

mixedList.Add("Second Group:");

for (int j = 5; j < 10; j++)

{

mixedList.Add(j);

}

// Display the elements in the list. Declare the loop variable by

// using var, so that the compiler assigns its type.

foreach (var item in mixedList)

{

// Rest the mouse pointer over item to verify that the elements

// of mixedList are objects.

Console.WriteLine(item);

}

Page 134: net notes

// The following loop sums the squares of the first group of boxed

// integers in mixedList. The list elements are objects, and cannot

// be multiplied or added to the sum until they are unboxed. The

// unboxing must be done explicitly.

var sum = 0;

for (var j = 1; j < 5; j++)

{

// The following statement causes a compiler error: Operator

// '*' cannot be applied to operands of type 'object' and

// 'object'.

//sum += mixedList[j] * mixedList[j]);

// After the list elements are unboxed, the computation does

// not cause a compiler error.

sum += (int)mixedList[j] * (int)mixedList[j];

}

// The sum displayed is 30, the sum of 1 + 4 + 9 + 16.

Console.WriteLine("Sum: " + sum);

// Output:

// Answer42True

// First Group:

// 1

// 2

// 3

// 4

// Second Group:

// 5

// 6

// 7

// 8

// 9

Page 135: net notes

// Sum: 30

Performance

In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally. For more information, see Performance.

Boxing

Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Consider the following declaration of a value-type variable:

VB

C#

C++

F#

JScript

Copy

int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

Page 136: net notes

VB

C#

C++

F#

JScript

Copy

// Boxing copies the value of i into object o.

object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure.

Boxing Conversion

It also possible to perform the boxing explicitly as in the following example, but explicit boxing is never required:

VB

Page 137: net notes

C#

C++

F#

JScript

Copy

int i = 123;

object o = (object)i; // explicit boxing

Description

This example converts an integer variable i to an object o by using boxing. Then, the value stored in the variable i is changed from 123 to 456. The example shows that the original value type and the boxed object use separate memory locations, and therefore can store different values.

Example

VB

C#

C++

F#

JScript

Copy

Page 138: net notes

class TestBoxing

{

static void Main()

{

int i = 123;

// Boxing copies the value of i into object o.

object o = i;

// Change the value of i.

i = 456;

// The change in i does not effect the value stored in o.

System.Console.WriteLine("The value-type value = {0}", i);

System.Console.WriteLine("The object-type value = {0}", o);

}

}

/* Output:

The value-type value = 456

The object-type value = 123

*/

The following example demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.

VB

C#

C++

F#

Page 139: net notes

JScript

Copy

class TestUnboxing

{

static void Main()

{

int i = 123;

object o = i; // implicit boxing

try

{

int j = (short)o; // attempt to unbox

System.Console.WriteLine("Unboxing OK.");

}

catch (System.InvalidCastException e)

{

System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);

}

}

}

This program outputs:

Specified cast is not valid. Error: Incorrect unboxing.

If you change the statement:

Copy

int j = (short) o;

Page 140: net notes

to:

Copy

int j = (int) o;

the conversion will be performed, and you will get the output:

Unboxing OK.

Unboxing

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:

Checking the object instance to make sure that it is a boxed value of the given value type. Copying the value from the instance into the value-type variable.

The following statements demonstrate both boxing and unboxing operations:

VB

C#

C++

F#

JScript

Copy

int i = 123; // a value type

object o = i; // boxing

int j = (int)o; // unboxing

The following figure demonstrates the result of the previous statements.

Unboxing Conversion

Page 141: net notes

For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

Introduction

The object class is the ultimate base class of every type. Because of its lofty position and significant influence on the code you write, you should have a good understanding of the object class and its members. You may also be interested in knowing why object exists in the first place. In this article, we look at these things with the goal of making you more aware of the rationale and use of the object class in your code.

Why an Object Class?

As the ultimate base class that all other other types directly or indirectly derive from, the object class allows you to build generic routines, provides Type System Unification, and enables working with groups of types as collections.  Common practice for implementing generic routines has been to write a method that accepts arguments of type object and allow users to pass in any type they want.  This approach is difficult to maintain because of the lack of type safety and inefficiency for value types.  I believe the practice of using the object class for generic routines will be replaced in many future scenarios by the use of Generics in C# v2.0.

Reference types inherit the object class either directly or through other reference types.  Value types inherit implicitly from the object class through System.ValueType.  In C#, the object class is a language specific alias for the .NET Base Class Library (BCL) type with the fully qualified name of System.Object.  Figure 1 shows the the relationships between the object class and other types.

Figure 1. The object class hierarchy has the System.Object type at the top.  Reference types inherit System.Object directly or through another reference type.  Value types implicitly inherit System.Object through the System.ValueType type.

Page 142: net notes

The ability of both reference types and value types to be treated as objects supports Type System Unification.  In many languages, built-in types such as int and float have no object-oriented properties and must be explicitly wrapped in objects to simulate object-oriented behavior.  However, C# eliminates the requirement to wrap built-in types through the concept of value types that inherit from System.ValueType, which inherits from System.Object.  This allows C# built-in types to be worked with in a manner similar to reference types.  From an object-oriented perspective, under Type System Unification both reference types and value types are objects.

Of course you don't get Type System Unification for free.  When assigning a value type to an object, behind the scenes, the system performs an extra operation referred to as Boxing.  After a boxing operation has completed, a value type is considered boxed. Similarly, when copying a boxed value type back to a normal value type, behind the scenes, the system performs another operation referred to as Unboxing.  While any value type can be boxed, it is not logical to assume that any reference type can be unboxed.  Only objects that have been previously boxed can be unboxed.  When a value type is boxed, a new object for that type is created in memory and the value of the value type is copied into that object.  During unboxing the value in the object is copied into the value of a value type.  Listing 1 shows a simple boxing/unboxing operation.

Listing 1.  Boxing and Unboxing

int myValType1 = 5;object myRefType = myValType1; // myValType is boxedint myValType2 = (int) myRefType; // myValType is unboxed

Although, for performance reasons, you need to be aware of the boxing/unboxing operations, the point being made here is that the object class, as the ultimate base class, promotes Type System Unification.  This makes it very simple to work with all types in the same manner for those times when such behavior in your application is necessary.

The object class also facilitates using any type in a collection.  It contains methods that can be reused or overridden in base types.  Since collections, such as Hashtable and ArrayList accept object types, you can add any type to them.  The Equals, GetType, and GetHashCode object class methods are called directly by the collection classes.  Other object class methods offer general capabilities that types have access to and can expose in their interface.

The Equals Method

A common operation, especially for searching and sorting in collections, is testing two objects for equality.  The Equals method of the object class provides a default implementation that compares two reference type objects for reference equality.  Reference equality occurs when two reference type objects refer to the same object.  Sometimes reference types need to define value equality instead of reference equality.  Fortunately, the Equals method is virtual, so derived reference types may override it.  An example is the string class, which overrides Equals to ensure that two strings are compared by the value of their strings.  Value types are compared for bitwise equality.  Listing 2 demonstrates how to use the Equals method with reference types.

Listing 2. Using the Equals Method

using System;

class Employee{    string m_name;    public Employee(string name)    {        m_name = name;

Page 143: net notes

    }}

class EqualsDemo{    static void Main()    {        EqualsDemo eqDemo = new EqualsDemo();        eqDemo.InstanceEqual();        Console.ReadLine();    }

    public void InstanceEqual()    {        string name = "Joe";        Employee employee1 = new Employee(name);        Employee employee2 = new Employee(name);

        // comparing references to separate instances        bool isEqual = employee1.Equals(employee2);

        Console.WriteLine("employee1 == employee2 = {0}", isEqual);

        employee2 = employee1;

        // comparing references to the same instance        isEqual = employee1.Equals(employee2);

        Console.WriteLine("employee1 == employee2 = {0}", isEqual);    }}

The demo in Listing 2 shows how the default implementation of Equals in the object class performs comparison on reference types.  In the InstanceEqual method the first comparison is of two separate instances of Employee, so the result of the call to Equals will be false.  Next, the reference to the object that employee1 refers to is assigned to employee2, making both references refer to the same instance.  This makes the next call to the Equals method return true.  To change the way Equals works, the Employee class could override Equals and provide an implementation based on equality of the m_name member.

There is also a static Equals method that performs the same task:  Object.Equals(object obj1, object obj2).

The ReferenceEquals Method

In the object class, the Equals and ReferenceEquals  methods are semantically equivalent, except that the ReferenceEquals works only on object instances.  The ReferenceEquals method is static. Listing 3 demonstrates how to use the ReferenceEquals method.

Listing 3. Using the ReferenceEquals Method.

using System;

class Employee{    string m_name;

Page 144: net notes

    public Employee(string name)    {        m_name = name;    }}

class ReferenceEqualsDemo{    static void Main()    {        ReferenceEqualsDemo refEqDemo = new ReferenceEqualsDemo();

        refEqDemo.InstanceEqual();

        Console.ReadLine();    }

    public void InstanceEqual()    {        string name = "Joe";

        Employee employee1 = new Employee(name);        Employee employee2 = new Employee(name);

        // comparing references to separate instances        bool isEqual = Object.ReferenceEquals(employee1, employee2);

        Console.WriteLine("employee1 == employee2 = {0}", isEqual);

        employee2 = employee1;

        // comparing references to the same instance        isEqual = Object.ReferenceEquals(employee1, employee2);        Console.WriteLine("employee1 == employee2 = {0}", isEqual);    }}

Notice that the code in Listing 2 and Listing 3 are the same except that Listing 3 uses the ReferenceEquals method.  The results are also the same.

The ToString Method

The purpose of the ToString method is to return a human readable representation of a type.  The default implementation in the object class returns a string with the name of the runtime type of the object.  Listing 4 demonstrates how to implement the ToString method in your own type.

Listing 4.  Implementing the ToString method.

using System;

class Employee{    string m_name;

    public Employee(string name)    {        m_name = name;

Page 145: net notes

    }

    public override string ToString()    {        return String.format("[Employee: {0}]", m_name);    }}

class ToStringDemo{    static void Main()    {        Employee emp = new Employee("Joe");

        Console.WriteLine(emp.ToString());

        Console.ReadLine();    }}

The ToString method in Listing 4 overrides ToString in the object class.  You can use ToString to facilitate debugging by providing human readable information about your type that can be viewed by developers inspecting program output emitted by calls to the ToString method.

The GetType Method

GetType is the basis for using reflection in .NET.  It returns a Type object, describing the object it was called on.  It can then be used to extract type member data like methods and fields that may subsequently be used for late-bound method invocations.  The GetType method is also useful if you get an object at runtime and you don't know what it's type is.  You can use the returned Type object to figure out what to do with the object.  Listing 5 demonstrates how to use the GetType method.

Listing 5.  Using the GetType Method.

using System;

class Employee{}

class GetTypeDemo{    static void Main()    {        object emp1 = new Employee();        Employee emp2 = new Employee();

        Console.WriteLine(emp1.GetType());        Console.WriteLine(emp2.GetType());

        Console.ReadLine();    }}

There are two instances of the Employee class created in the Main method of Listing 5.  The first is assigned to a reference of type object and the second is assigned to a reference of type

Page 146: net notes

Employee.  When run, the program will print "Employee" as the result of the call to GetType.  This shows that GetType returns the run-time type of the object it is called on, rather than the compile-time reference it is assigned to.  The reason the program could get a string out of the call to GetType is because it returns a Type object, which overrides the ToString method used by Console.WriteLine.

The GetHashCode Method

The GetHashCode method makes any object usable in a Hashtable or any hashing algorithm.  Since the default algorithm supplied by the GetHashCode method of the object class is not guaranteed to be unique, you should override GetHashCode in your custom types.  Listing 6 demonstrates how to implement a custom GetHashCode method.

Listing 6.  Implementing a GetHashCode method.

using System;

class Employee{    string m_name;

    public Employee(string name)    {        m_name = name;    }

    public override int GetHashCode()    {        string uniqueString = ToString();

        return uniqueString.GetHashCode();    }

    public override string ToString()    {        return String.format("[Employee: {0}]", m_name);    }}

class GetHashCodeDemo{    static void Main()    {        Employee emp = new Employee("Joe");

        Console.WriteLine(emp.GetHashCode());

        Console.ReadLine();    }}

The Employee class in Listing 6 overrides the GetHashCode method to provide a unique number for each unique instance of the Employee class.  This is accomplished by using the ToString method that will return a string uniquely representing the value of this instance.  Then GetHashCode is called on the string and returned to the caller.  The benefits of using the string class is that it already has a GetHashCode function that can be used. The GetHashCode method of the string class returns a random distribution of hash codes, guarantees codes are unique for

Page 147: net notes

different strings, and ensures codes are identical for the same strings.  Although not shown in this example for the sake of brevity, types that implement GetHashCode should also implement Equals for Hashtable support.

The MemberwiseClone Method

Whenever you need to create a shallow copy of your type, use the MemberwiseClone method.  A shallow copy is a bitwise copy of your type.  As such, if you perform a MemberwiseClone on your class, it will make a copy of the type and all contained value types and references types.  However, it will not copy the objects that the reference type members in your type refer to.  This behavior of only making a copy of the first level of your type demonstrates the reason why a MemberwiseClone is called a shallow copy.  Since the MemberwiseClone method is not virtual, you can not override it in derived classes. You should implement the IClonable interface if you need a deep copy.  Listing 7 shows how to use MemberwiseClone.

Listing 7.  Using the MemberwiseClone Method.

using System;

public class Address{}

class Employee{    Address m_address = new Address();    string m_name;

    public Employee(string name)    {        m_name = name;    }

    public Employee ShallowCopy()    {        return (Employee)MemberwiseClone();    }

    public Address EmployeeAddress    {        get        {            return m_address;        }    }}

class MemberwiseCloneDemo{    static void Main()    {        Employee emp1 = new Employee("Joe");        Employee emp2 = emp1.ShallowCopy();

        // compare Employee references        bool isEqual = Object.ReferenceEquals(emp1, emp2);

Page 148: net notes

        Console.WriteLine("emp1 == emp2: {0}", isEqual);

        // compare references of Address object in each Employee object        isEqual = Object.ReferenceEquals(emp1.EmployeeAddress, emp2.EmployeeAddress);

        Console.WriteLine("emp1.EmployeeAddress == emp2.EmployeeAddress: {0}", isEqual);

        Console.ReadLine();    }}

Since MemberwiseClone has protected visibility, Listing 7 wraps the call to it in the ShallowCopy method of the Employee class.  When the Main method calls ShallowCopy, the emp2 variable holds a reference to a copy of emp1.  However, this is a shallow copy, as subsequent statements prove.  The first call to ReferenceEquals shows that the emp1 and emp2 variables refer to separate instances.  The second call to ReferenceEquals performs a comparison on the Address object within the emp1 and emp2 instances.  The comparison demonstrates that both of the Address references point to the same object, proving that only a shallow copy has been performed.

The Finalize Method

Although the object class has a Finalize method, it is not available to C# programs in that form.  Instead, you would use what is called a destructor in C#, which is synonymous with the Finalize method.  In further discussion, I'll refer to the Finalize method as a destructor.  The original purpose of the destructor was to serve as a place where you can release unmanaged resources such as network connections, operating system resources, or file streams.  However, in practice you never want to use the destructor.  The reason is that a destructor is executed in non-deterministic time, meaning that you have no way of knowing when it will be run and no way to know when your resources will be released.  Developers familiar with C++ will notice that this is a distinct difference in destructor behavior because in C++ a destructor is executed deterministically, as soon as an object is freed.  The solution to this problem in C# is to implement the IDisposable interface on all your types that need to release unmanaged resources.  Listing 8 shows a class that implements a destructor.

Listing 8.  Implementing a Destructor

using System;

class Employee{    string m_name;

    public Employee(string name)    {        m_name = name;    }

    ~Employee()    {        Console.WriteLine("Employee destructor executed.");    }}

class DestructorDemo{    static void Main()

Page 149: net notes

    {        Employee emp = new Employee("Joe");

        Console.ReadLine();    }}

The Employee class in Listing 8 implements a destructor.  Destructors are prefixed with a tilde and named the same as their containing class.  Additionally, they do not have parameters.  Value types do not have destructors.  If you run this program it will not print anything to the console and will wait for you to press the Enter key.  Since it is so small, it will not consume enough memory resources to force a garbage collection, which in turn would call the destructor.  In fact, the program will set there forever and the destructor may never be called if you don't ever press the Enter key.  If the program was holding an unmanaged resource, the unmanaged resource would not be released.  When you do press the enter key, the CLR will initiate a garbage collection and the program will print "Employee destructor executed." to the screen when the garbage collector calls the destructor, prior to final program shutableown.  If you are using an IDE, this message will flash on the screen quickly as the console goes away.  To see the message, open a console window and run the executable program on the command line.

There are a couple arguments that are for and against using destructors -- both agree that the Dispose pattern should be implemented.  One of these arguments states that a destructor should be implemented as a fall-back in case code that uses your class doesn't implement the Dispose pattern properly (or at all).  They view the destructor as a safety net.  Another argument states that destructors should never be implemented.  This point of view regards destructors as dangerous because they give the implementer a false sense of safety.  For instance, if there were a problem with the code in the destructor you wouldn't know it until the destructor was executed, which may never happen at all.  Because destructor execution is non-deterministic, you have a non-deterministic problem to solve, which may be very difficult and nearly impossible to reproduce and fix.  Having worked on many mission critical systems and having to overcome the perils of fixing production problems, I support the second argument that states you should not use destructors.  You should learn how to implement the IDisposable (The Dispose Pattern) interface properly.

Conclusion

As the ultimate base class of all .NET types, the object class is very important.  It contains several methods that you need to be aware of.  You need to know how to use and implement overrides of some of these methods as appropriate for building well-behaved custom types.  Most of the discussion about object class methods begs for more information, which I'll follow up with in subsequent articles. This has been an overview that illuminates key points that should be useful in your development endeavors.

EXTENSION METHODS

Extension Methods are just one of the many impressive features introduced with C# 3.0 (along with the Implicitly Typed Local Variables, Lambda Expressions, LINQ and other wonders of the .NET)

Sure, you will say, even kindergarten developers know that! But what exactly are those Extension Methods? What kind of magic makes them possible and how / when (not) to use them?

  In this article we will first briefly examine this new language feature, show some basics usages and then we will tackle some more advanced and concrete examples of Extension Methods used to provide natural DateTime operations (similar to Date and

Page 150: net notes

Time operations available in Ruby on Rails) so be sure to stay tuned!

First of all lets start looking at the roots of it and see what the almighty MSDN Documentation says on this subject:

“Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. “

Well that sure sounds nice! Until now we were kind of stuck with the existing built-in classes and types, and in order to extend them we had to inherit the new class from them and then add new functionality (if we were lucky enough that the original class is not marked as Sealed).

So with Extension Methods we get some new degrees of freedom.

We can add functionality to any existing class (for now only in the form of new static methods, but who knows, we might get some more options in the future, like Extension Properties and Extension Events etc).

Off course there are some limitations:

Extension Methods have to be implemented as static methods and in static classes (inside a non-nested, non-generic static class to be more precise).

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

Extension methods cannot access private variables in the type they are extending.

You can consider Extension Methods as a 'legal' way to add more static methods to existing classes without actually inheriting them.

But the funny thing is that unlike regular static methods of the class, you cannot call Extension Methods on a class level (you will get an compile time error if you try this), but instead you must invoke them on a instance of the class (as if they were some regular methods of the instance of that class, which they are not!!!).

Also, inside the Extension Method you can freely use public properties of the passed object instance on which the method is being invoked, you are by no means limited only to static object data. Only the Extension Method is static method, but the object on which is called is full, regular object instance.

Its little confusing but don't worry you will get used to it as soon as you start using it.

How this works under the hood? (again MSDN to the rescue):

"In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method. Therefore, the principle of encapsulation is not really being violated."

Ok, lets start with some simple "Hello World" example (for those of you that want more advanced examples, be patient we will get to that soon, or just skip to the end of article):

Motivation: We will add a single Extension Method called Reverse() to the System.String class that will return the reversed copy of the string on which we will call this method.

First we must create a static class with the Reverse() static method. Also we will define it inside a namespace so we can later import that Extension Method in our projects:

using System; namespace StringExtensionMethods{    public static class StringHelpers    {

        public static string Reverse (this string s)        {            char[] letters = s.ToCharArray();            Array.Reverse(letters);

Page 151: net notes

            return new string(letters);        }    }}

If you look at Reverse() method signature you can notice the 'this' keyword that is mandatory when creating Extension Methods (this keyword actually tells the compiler that we are creating one).

Also you can see that 'this' keyword is followed by the actual type that we are extending (in this case its string type) and after this there is a name of the parameter (so we can reference it in the methods implementation) and we can choose the name as we wish, no especial limitations there.

Make note that the 'string s' parameter that the static method will receive will be the instance of the object on which we are calling the actual Extension Method.

IMPORTANT: Remember that when we will call the Reverse() method there is no need to pass that first parameter, runtime will do that 'automagically' for us. But more on that later.

So first lets see how to use this Reverse() method:

In our project we must include the namespace where we defined the Extension Method so that it become available.

using StringExtensionMethods;

And then in our code we can write:

string word = "alpha";

Console.WriteLine(word.Reverse());

and the text that will be printed in the console will be “ahpla”.

As we have already said, you see there is no need to pass the first parameters to our Extension Method because the instance of the object on which we are calling it is passed as the first parameter.

Off course, that does not mean we cannot pass any parameters!

We can add more parameters to the the method signature and then pass them when calling the extension method.

But the first parameter will always be the instance of the object we are using the method on.

We can optionally define (in Extension Method signature) and later (when calling) provide arguments for parameters 2 through n.

So lets quickly create an example with additional parameter. This time we will extend System.Int type and add to it MultiplyBy() method that will allow us to easily multiply any integer with another integer.Here is the implementation: 

namespace IntExtensionMethods{    public static class IntHelpers    {        public static int MultiplyBy(this int originalNumber, int numberToMultiplyWith)        {            return originalNumber * numberToMultiplyWith;        }    }}

You see that we have added the second Int parameter to the method signature and we use it to multiply the original number with this second parameter called numberToMultiplyWith.

And here is how to use it:

First we must not forget to add the namespace to our using list:

using IntExtensionMethods;

Page 152: net notes

and then call our method on the instance of any Int with single parameter (as we said many times so far, the first parameter - the actual Int value on which we are calling the method - is passed by runtime so we dont have to do it):

int resultShouldBeTwelve = 3.MultiplyBy(4);Console.WriteLine(result.ToString());

Thats about it. Now we know how to use Extension Methods!

But wait, we are not finished yet! This is where all the fun begins.

Lets do some real magic. Imagine we have a project that will be heavily using DateTime object and making a lot of complex date and time calculations.

Even with all the nice functionality built-in into DateTime class still its sometimes tedious to do time calculations.

If you want to add two weeks to some DateTime instance here is how we would normally had to do it:

DateTime nextWeek = DateTime.Now + new TimeSpan(14, 0, 0, 0);

or the other way:

nextWeek = DateTime.Now + TimeSpan.FromDays(14);

Looks a little messy, right?  Wouldn't it be more natural for us as humans to write our code something like this:

DateTime nextWeek = DateTime.Now + 2.Weeks();

or even nicer: 

DateTime twoWeeksFromNow = 2.Weeks().FromNow();

Well, hold your breath, because with extension methods its very easy to accomplish this.

For example, here is the Extension Method for the System.Int32 class that returns TimeSpan of the length of the number of weeks depending on the value of the number (Int) on which you call it:

/// <summary>/// Returns TimeSpan for given number of Weeks (number of weeks * 7)/// </summary>/// <param name="weeks"></param>/// <returns></returns>public static TimeSpan Weeks(this int weeks){    return new TimeSpan(weeks * 7, 0, 0, 0, 0);}

But this is just scratching the surface.

Here is some more functionality we could easily achieve combining that with more similar Extension Methods:

DateTime tomorrow = DateTime.Now + 1.Days();DateTime yesterday = DateTime.Now - 1.Days();           DateTime changedHourTo14h = DateTime.Now.SetHour(14);DateTime todayNoon = DateTime.Now.Noon();DateTime tomorrowNoon = DateTime.Now.NextDay().Noon();DateTime fiveDaysAgo = 5.Days().Ago();DateTime twoDaysFromNow = 2.Days().FromNow();DateTime nextYearSameDateAsTodayNoon = 1.Years().FromNow().Noon(); 

Now how about that ??? 

If you got interested make sure you check out my CodePlex project Fluent DateTime that provides these and many more nice Extension Methods for handling DateTime.

Page 153: net notes

If you have some ideas you can join the project and contribute to the .NET community.

 

This wraps up our journey to the Extension Methods.

Now before you get all excited and start writing them for each class in System namespace just one final note of warning:

Make sure that you don't use this powerful feature without self-control.

If used when not really necessary you are opening the Pandora's Box and you can make your code less readable, or you can find yourself writing Extension Methods to some class and instead what you should have done is to extend that class and add those methods to the descendant classes lower down the class hierarchy...

Here is what MSDN says on this subject:

“Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible.”

So use it, but wisely! 

EXTENSION METHODS

You want to improve the syntax for calling common methods in your C# program, so that function names are shorter and easier to type. Extension methods in the C# programming language provide a way to easily represent static methods as instance methods in the syntax of the C# language, which can be more intuitive and recallable for developers. Here we look at extension methods.

Use extension methods

Here is a custom extension method defined in a program written in the C# programming language. Generally, you will want to store your extension method class in a separate source file, such as "ExtensionMethods.cs" in your project. The file should store a static

Page 154: net notes

class with public static extension methods. In the rest of your source code, you can invoke these extension methods in the same way as you can call instance methods.

Program that uses extension method on string [C#]

using System;

public static class ExtensionMethods{ public static string UppercaseFirstLetter(this string value) // Note parameter declaration. {

//// Uppercase the first letter in the string this extension is called on.//if (value.Length > 0){ char[] array = value.ToCharArray(); array[0] = char.ToUpper(array[0]); return new string(array);}return value;

}}

class Program{ static void Main() {

//// Use the string extension method on this value.//string value = "dot net perls";value = value.UppercaseFirstLetter(); // Called like an instance method.Console.WriteLine(value);

}}

Output

Dot net perls

Declaring extension method in static class. In the first part of the program text, you can see an extension method declaration in the C# programming language. An extension method must be static and can be public so you can use it anywhere in your source code. The extension method is called like an instance method, but is actually a static method. The instance pointer 'this' is received as a parameter. You must specify the 'this' keyword before the appropriate parameter you want the method to be called upon. In the method, you can refer to this parameter by its declared name.

This-keyword in parameter list. The only difference in the declaration between a regular static method and an extension method is the 'this' keyword in the parameter list. If you want the extension method to received other parameters as well, you can place those in the method signature's parameter list after the 'this' parameter.

Calling extension method. You can call an extension method in the same way you call an instance method. In Visual Studio, an extension method in IntelliSense is represented by a different icon that has a downward arrow on it. You can use this icon to differentiate between instance and extension methods before calling them. Also the text "(extension)" is used in IntelliSense.

Page 155: net notes

Common extension methods used

There are many extension methods available in the .NET Framework currently used. These extension methods were written by Microsoft and are available in all C# programs targeting recent versions of the .NET Framework. On most of the extension methods, you need to add the "using System.Linq" directive to the top of the source text. The articles on this site detail many of these extensions.

FirstOrDefault Method Average Extension Method First Extension Method Skip Extension Method Sum

Method ToArray Extension Method

More parameters

Extension methods can have many arguments other than the 'this' parameter that is required. You can even use variable 'params' arguments with extension methods, as with any method. Because extension methods are actually static methods, there is no significant performance difference between them and other methods. Extension methods are basically an altered-syntax form of instance methods in the C# programming language. They affect the high-level representation of the source text, not the low-level implementation.

Summary

We examined extension methods in the C# programming language, first seeing an example that uses an extension method to uppercase letters in methods. The extension method shown uses the string type and extends it with a new method. You can add extension methods to any type, even value types, and the original representation of the type does not change. Extension methods affect the syntactic representation of the source, but do not make the execution of the source code substantially different.


Recommended