Month: November 2017



I will be blogging on ASP.NET and publishing on the following topics of ASP.NET 4.0

Introduction to ASP.NET

  • Agenda :
    • Brief on HTML
    • Difference between HTML and XML
    • Why XML is important.
    • Static Web Pages vs Dynamic Web Pages.
    • TAG affect how text is displayed on Web Page. E.g. <b> text </b> <i> italic</i> è text italic.

<b color=blue> this</b> this

Difference between Web Forms   and ASP.NET MVC 3.0

                        Web Forms                                MVC
  •   Web Forms are based on ASP.NET and it is high   level programming framework.
ASP.NET   MVC is also based on ASP.NET and it is low level programming technology.
  •   Web Forms are similar to User Interface   controls of windows App. It is event based controls.
ASP.NET   MVC uses HTML controls and requires knowledge of JS plugins.
  •   Web Forms Controls encapsulate HTML, JS and   CSS. They databind Charts, Grid, Tables etc.
ASP.NET   MVC directly use HTML controls hence require deep knowledge of HTML and HTTP.   They have total control of HTML markup.
  •   The unit testing is not part of the framework,   needs to be manually incorporated.
ASP.NET   MVC supports unit testing, TDD and Agile.
  •   Browser differences are handled by the Web   Forms
Browser   differences and OS compatibility needs to be care by the developer.

What is ASP.NET

ASP.NET is free framework using C# and VB. Visual studio provides Visual Web Developer for free to develop standalone website. The Intellisense of Visual Studio helps to understand the libraries used for developing website. Visual Studio has powerful debugging tool. ASP.NET is part of .NET, Website Spark is a development program to develop website and it is free software.

How text is   displayed Provides information about the text
HTML is parsed and interpreted by browser and then   displayed. Using XML to provide a data for information requested and provides   the data as response in XML.
Static Web Pages Dynamic Web Pages
A plain HTML page which doesn’t change   during interaction with the user is Static Web Page. An .aspx page is analyzed and CLR   executes code in it by server to generate dynamic page. Finally the response   data is converted to HTML page for each request.

Working with the Server

  • Server does everything for every user request.
  • Dynamic Page forces Server to do everything lead to poor performance.
  • Server manages the HTTP state session.

The .aspx page is a dynamic page follows the request and response model. And it has unique session for each request.

Client information and session information to recognize the request originate information for the server.

When 1st request is sent, server creates session and is managed by server. Session management require server resources. Time out limit is set by the web application, after limit the session expires. So before the session expires an interaction between the client and server should be made.

1st request à Parser à compile à IL code in Assembly Cache à Memory Execute http runtime.

2nd request ——————————————————————àMemory Execute http runtime.

Server Controls

Server Control : Server control is configured before hand during design time. The  request for the web page makes the dynamic page to execute the program logic at the server and deliver it as HTML control to client. E.g. gridView control, calendar control.

Code Behind: VB/C# code in another page with extension .cs is code behind of web page.

Inline Code: Javascript code and HTML tags are inline code in web page.

ASP.NET Framework which is composed of WebMatrix, WebForms, ASP.NET MVC is required to build websites, web application.

State Management and AutoPostback

Web pages are HTTP based and are stateless, the stateless nature is a problem.

ASP.NET maintains the HTTP state automatically. set EnableViewState to true in properties window to enable Postback.

What is ViewState ? ViewState  is a hidden value containing state information.

Autopostback – When a  whole page is sent back to server with new option selected is a AutopostBack property.

ASP.NET supports client side scripting.

Validation controls: A special control under validation section in toolbox; Select required control in it and drop  them on the web design. Select the control to validate. Only works with Server controls. So Validation controls to works with HTML convert html control to Server control.


.NET Application Packaging, Deployment and Configuring Application

Deployment and Packaging .NET Assemblies.
Deployment and Packaging of .NET Application
Today, applications are created using the types developed by Microsoft or custom built by you. If these types are developed using any language that targets the common language runtime (CLR), they can all work together seamlessly, i.e. different types created using different .NET languages can interact seamlessly.

.NET Framework Deployment Objectives:

All applications use DLLs from Microsoft or other vendors. Because an application executes code from various vendors, the developer of any one piece of code can’t be 100 percent sure how someone else is going to use. Even if this kind of interaction is unsafe and dangerous. End users have come across this scenario quiet often when one company decides to update its part of the code and ship it to all its users. Usually these code should be backward-compatible with previous version, since it becomes impossible to retest and debug all of the already-shipped applications to ensure that the changes will have no undesirable effect.

When installing a new application you discover that it has somehow corrupted an already-installed application. This predicament is known as “DLL hell”. The end result is that users have to carefully consider whether to install new software on their machines.

The problem with this is that the application isn’t isolated as a single entity. You can’t easily back up the application since you must copy the application’s files and also the relevant parts of the registry you must run the installation program again so that all files and registry settings are set properly. Finally, you cant easily uninstall or remove the application without having this nasty feeling that some part of the application is still lurking on your machine.

When application are installed, they come with all kinds of files, from different companies. This code can perform any operation, including deleting files or sending e-mail. To make users comfortable, security must be built into the system so that the users can explicitly allow or disallow code developed by various companies to access their system resources.

The .NET framework addresses the DLL hell issue in a big way. For example, unlike COM, types no longer require settings in the registry. Unfortunately, application still require shortcut links. As for security, the .NET Framework includes a security model called code access security   Whereas Windows security is based on a user’s identity, code access security is based on permissions that host applications that loading components can control. As you’ll see, the .NET Framework enables users to control what gets installed and what runs, and in general, to control their machines, more than Windows ever did.

Developing Modules with Types

Lets start with an example as shown below:

public sealed class Appln {

public static void Main() {

System.Console.WriteLine(“Hello My world”);



This application defines type called Appln. This type has a single public, static method called Main. Inside Main is a reference to another type called System.Console. System.Console is a type implemented by Microsoft, and the intermediate Language (IL) code that implements this type’s methods is in the MSCorLib.dll file. To build it write the above source code into a C# file and then execute the following command line:

csc.exe /out : Appln.exe /t:exe /r:MSCorLib.dll Appln.cs

This command line tells the C# compiler to emit an executable file called Appln.exe (/out: Appln.exe). The type of file produced is a win32 console application (/t[arget]:exe).

When the C# compiler processes the source file, it sees that the code references the System.Console type’s WriteLine method. At this point, the compiler wants to ensure that this type exists somewhere, that it has a WriteLine method, and that the argument being passed to this method matches the parameter the method expects. Since this type is not defined in the C# source code, to make the C# compiler happy, you must give it a set of assemblies that it can use to resolve references to external types. In the command line above /r[eference]:MSCorLib.dll switch, which tells the compiler to look for external types in the assembly identified by the MSCorLib.dll file.

MSCorLib.dll is a special file in that contains all the core types: Byte, Char, String, Int32 and many more. In fact these types are so frequently used that the C# compiler automatically references the MSCorLib.dll assembly. i.e. the above command line can be shortened as

csc.exe /out : Appln.exe /t:exe Appln.cs

Further you can drop /out and /t:exe since both match, so the command would be

csc.exe Appln.cs

If for some reason, you really don’t want the C# compiler to reference the MSCorLib.dll assembly, you can use the /nostdlib switch. Microsoft uses this switch when building the MSCorlib.dll assembly itself. For e.g. the following will throw error since the above code references System.Console type which is defined in MSCorLib.dll

csc.exe /out: Appln.exe /t:exe /nostdlib Appln.cs

This means that a machine running 32-bit or 64-bit versions of Windows should be able to load this file and do something with it. Windows supports two types of applications, those with a console user interface (CUI) and those with a graphical user interface (GUI). Because I specified the /t:exe switch, the C# compiler produced a CUI application. You’d use the /t: winexe switch to cause the C# compiler to produce a GUI application.

Response Files

I’d like to spend a moment talking about response files. A response file is a text file that contains a set of compiler command-line switches. You instruct the compiler to use a response file by specifying its name on the command line by an @sign. For e.g. you can have response file called myApp.rsp that contains the following text

/out: MyAppln.exe

/target: winexe

To cause CSC.exe to use these settings you’d invoke it as follows:

csc.exe @myAppln.rsp codeFile1.cs CodeFile2.cs

This tells the C# compiler what to name the output file and what kind of target to create. The C# compiler supports multiple response files. The compiler also looks in the directory containing the CSC.exe file for a global CSC.rsp file. Settings that you want applied to all of your projects should go in this file. The compiler aggregates and uses the settings in all of these response files. If you have conflicting settings in the local and global response file, the settings in the local file override the settings in the global life. Likewise, any settings explicitly passed on the command line override the settings taken from a local response file.

When you install the .NET Framework, it installs a default global CSC.rsp file in the %SystemRoot%\Microsoft.NET\Framework\vX.X.Xdirectory where X.X.X is the version of the .NET Framework you have installed). The 4.0 version of the file contains the following switches.

# This file contains command-Line options that the C# Compiler has to process during compilation

# process, unless “noconfig” option is specified.

# Reference the common Framework libraries

/r: Accessibility.dll

/r: Microsoft.CSharp.dll

/r: System.Configuration.Install.dll

/r: System.Core.dll

/r: System.Data.dll

/r: System.Data.DataSetExtensions.dll

/r: System.Data.Linq.dll

/r: System.Deployment.dll

/r: System.Device.dll

/r: System.DirectoryServices.dll

/r: System.dll

/r: System.Drawing.dll

/r: System.EnterpriseServices.dll

/r: System.Management.dll

/r: System.Messaging.dll

/r: System.Numerics.dll

/r: System.Runtime.Remoting.dll

/r: System.Runtime.Serialization.dll

/r: System.Runtime.Serialization.Formatters.Soap.dll

/r: System.Security.dll

/r: System.ServiceModel.dll

/r: System.ServiceProcess.dll

/r: System.Transactions.dll

/r: System.Web.Services.dll

/r: System.Windows.Forms.dll

/r: System.Xml.dll

/r: System.Xml.Linq.dll

Because the global CSC.rsp file references all of the assemblies listed, you do not need to explicitly references all of the assemblies by using the C# compiler’s /reference switch. This response file is a big convenience for developers because it allows them to use types and namespaces defined in various Microsoft-published assemblies without having to specify a /reference compiler switch for each when compiling.

When you use the /reference compiler switch to reference an assembly, you can specify a complete path to a particular file. However, if you do not specify a path, the compiler will search for the file in the following places (in the order listed)

– working directory

– The directory that contains the CSC.exe file itself. MSCorLib.dll is always obtained from the directory. The path looks something like this %SystemRoots%\Microsoft.NET\Framework\v4.0.#####

– Any directories specified using the /lib compiler switch.

– any directories specified using the LIB environment variable

you are welcome to add your own switches to the global CSC.rsp file if you want to make your life even easier, but this makes it more difficult to replicate the build environment on different machines you have to remember to update the CSC.rsp the same way on each build machine. Also you can tell the compiler to ignore both local and global files by specifying the /noconfig command-line switch.

A managed PE file has four main parts the PE32(+) header, the CLR header, the metadata and the IL . the PE32(+) header is the standard information that Windows expects. The CLR header is a small block of information that is specific to modules that require the CLR (managed modules). The header includes the major and minor version number of the CLR that the module was built for: some flags, a MethodDef token (described later) indicating the module’s entry point method if this module  is CUI or GUI executable, and an optional strong-name. You can see the format of the CLR header by examining the IMAGE_COR20_HEADER defined in the CorHdr.h header file.

The metadata is a block of binary data that consists of several tables. There are three categories of tables: definition tables, reference tables and manifest tables. The following table describes some of the more common definition tables that exist in a module’s metadata block.

Metadata Definition
Table Name
ModuleDef Always contains one entry that identifies the module. The entry includes the module’s filename and a extension and a module version ID. This allows the file to be  renamed while keeping a record of its original name.
TypeDef Contains one entry for each type defined in the module. Each entry includes the type’s name, base type and flags (public, private etc, ) and contains indexes to the methods it owns in the MethodDef table, the fields it owns in the fieldDef table, the properties it owns in the PropertyDef table, and the events it owns in the EventDef table.
MethodDef Contains one entry for each method defined in the module. Each entry includes the method’s name, flags (private, public, virtual, abstract, static, final, etc) signature and offset within the module where its IL code can be found. Each entry can also refer to a ParamDef table entry in which more information about the method’s parameters can be found.
FieldDef Contains one entry for every defined in the module. Each entry includes flags (in, out, retval, etc) type and name.
ParamDef Contains one entry for each parameter defined in the module. Each entry includes flags (in, out, retval etc) type and name.
PropertyDef Contains one entry for each property defined in the module. Each entry includes flags, type and name.
EventDef Contains one entry for each event defined in the module. Each entry includes flags and name.

Compiler during compilation creates an entry for every definition in the source code to be created in one of the tables defined above. Metadata table entries are also  created as the compiler detects the types, fields, methods, properties and events that the source code references. The metadata created includes a set of reference tables that keep a record of the referenced items. Table below gives some more common reference metadata tables.

Metadata Reference
Table Name
AssemblyRef Contains one entry for each assembly referenced by the module. Each entry includes the information necessary to bind to the assembly: the assembly’s name (without path and extension), version number, culture and public key token. Each entry also contains some flags and a hash value.
ModuleRef Contains one entry for each PE module that implements types referenced by this module. Each entry includes the module’s filename and extension. This table is used to bind to types that are implemented in different modules of the calling assembly’s module.
TypeRef Contains one entry for each type referenced by the module. Each entry includes the type’s name and a reference to where the type can be found. If the type is implemented within another type, the reference will indicate a TypeRef entry. If the type is implemented in the same module , the reference will indicate a ModuleDef entry.  If the type is implemented in the another module within the calling assembly , the reference will indicate a ModuleRef entry. If the type is implemented in the different assembly, the reference will indicate a AssemblyRef entry.
MemberRef Contains one entry for each member referenced by the module. Each entry includes the member’s name and signature and points to the TypeRef entry for the type that defines the member.

My personal favorite is ILDasm.exe, the IL Disassembler. To see the metadata tables, executes the following command line

ILDasm MyAppln.exe

To see the metadata in a nice, human-readable form, select the View/MetaInfo/Show! menu item.

The important thing to remember is that MyAppln.exe contains a TypeDef whose name is MyAppln. This type identifies a public sealed class that is derived from System.Object (a type referenced from another assembly). The program type also defines two methods Main and .ctor (a constructor).

Main is a public, static method whose code is IL. Main has a void return type and takes no arguments. The constructor method is public and its code is also IL. The constructor has a void return type has no arguments and has a this pointer,  which refers to the object’s memory that is to be constructed when the method is called.

Combining Modules to Form an Assembly

An assembly is a collection of one or more files containing type definitions and resource files. One of the assembly’s files is chosen to hold a manifest. The manifest is another set of metadata tables that basically contain the names of the files that are part of the assembly. They also describe the assembly’s version, culture, publisher, publicly exported types and all of the files that comprise the assembly.

The CLR always loads the file that contains the manifest metadata tables first and then uses the manifest to get the names of the other files that are in the assembly. Here are some characteristics of assemblies that you should remember:

– An assembly defines the reusable types.

– An assembly is marked with a  version number.

– An assembly can have security information associated with it.

An assembly’s individual files don’t have these attributes – except for the file that contains the manifest metadata tables. To package, version, secure and use types, you must place them in modules that are part of an assembly

The reason is that an assembly allows you to decouple the logical and physical notion of reusable types. for e.g. an assembly can consist of several types. You couldn’t put the frequently used types in one file and the less frequently used types in another file.

You configure an application to download assembly files by specifying a codeBase element in the application’s configuration file. The codeBase element identifies a URL pointing to where all of an assembly’s files can be found. When attempting to load an assembly’s file, the CLR obtains the codeBase element’s URL and checks the machine’s download cache to see if the file is present. If it is, the file is loaded. If the file isn’t in the cache, the CLR downloads the file into cache from the location the URL points to. If the file can’t be found, the CLR throws a FileNotFoundException exception at runtime.

I’ve identified three reasons to use multifile assemblies:

– You can partition  your types among separate files, allowing for files to be incrementally downloaded as described in the Internet download scenario. Partitioning the types into separate files also allows for partial or piecemeal packaging and deployment for applications you purchase and install.

-You can add resource or data files to your assembly. for example, you could have a type that calculates some insurance information using actuarial table. Instead of embedding the actuarial table in the source code, you could use a tool so that the data file is considered to be part of  the assembly.

-You can create assemblies consisting of types implemented in different programming languages. To developers using the assembly, the assembly appears to contain just a bunch of types; developers wont even know that different programming languages were used. By the way, if you prefer, you can run ILDasm.exe on each of the modules to obtain an IL source code file. Then you can run ILAsm.exe and pass it all of the IL source code files. ILAsm.exe will produce a single file containing all of the types. This technique requires your source code compiler to produce IL-only code.

Manifest Metadata
Table Name
AssemblyDef Contains a single entry if this module identifies as assembly. The entry includes the assembly’s name, version, culture, flags, hash algorithm, and the publisher’s public key.
FileDef contains one entry for each PE and resource file that is part of the assembly. The entry includes the file’s name and extension, hash value and flags. If the assembly consists only of its own file, the FileDef table has no entries.
ManifestResourceDef Contains one entry for each resource that is part of the assembly. The entry includes the resource’s name, flags and an index into the FileDef table indicating the file that contains the resource isn’t a stand-alone file, the resource is a stream contained within a PE file. For an embedded resource, the entry also includes an offset indicating the start of the resource stream within the PE file.
ExportedTypesDef Contains one entry for each public type exported from all of the assembly’s PE modules. The entry includes the type’s name, an index into the FileDef table and an index into the TypeDef table. To save file space, types exported from the file containing the manifest are not repeated in this table because the type information is available using the metadata’s TypeDef table.

The C# compiler produces an assembly when you specify any of the following command-line switches: /t[arget]:exe, /t[arget]:winexe or t[arget]:library. All of these switches cause the compiler to generate a single PE file that contains the manifest metadata tables. The resulting file is either a CUI executable, GUI executable or a DLL, respectively.

The C# compiler supports the /t[arget]:module switch. This switch tells the compiler to produce a PE file that doesn’t contain the manifest metadata tables. The PE file produced is always a DLL PE file, and this file must be added to an assembly before the CLR can access any types within it. When you use the /t:module switch, the C# compiler, by default, names the output file with an extension of .netmodule.

There are many ways to add a module to an assembly. If you are using the  C# compiler to build a PE file with a manifest, you can use the /addmodule switch. Let’s assume that we have two source code files:

– File1.cs which contains rarely used types

– File2,cs which contains frequently used types

Lets compile the rarely used types into their own module so that users of the assembly won’t need to deploy this module if they never access the rarely used types:

csc /t:module File1.cs

This line causes the C# compiler to create a File1.netmodule file. Next let’s compile the frequently used types into their module, because this module will now represent the entire assembly.

We change the name of the output file to myappln.dll instead of calling it File2.dll

csc /out:File2.dll /t:library /addmodule:File1.netmodule File2.cs

This line tells the C# compiler to compile the File2.cs  file to produce the myappln.dll file Because /t:library is specified, a DLL PE file containing the manifest metadata tables is emitted into the myappln.dll file. The /addmodule:File1.netmodule switch tells the compiler that File1.netmodule is a file that should be considered part of the assembly. Specifically, the addmodule switch tells the compiler to add the file to the FileDef manifest metadata table and to add File1.netmodule’s publicly exported types to the ExportedtypesDef manifest metadata table.

The two files shown below are created. The module on the right contains the manifest.

File1.netmodule myappln.dll
IL compiled from File1.cs IL compiled from File2.cs
Metadata Types, methods and so on defined by file1.csTypes, methods and so on referenced by File1.cs Metadata Types, methods and so on defined by file2.csTypes, methods and so on referenced by File2.cs

Manifest Assembly files (self and File2.netmodule)
Public assembly types (self and File2.netmodule)

The File1.netmodule file contains the IL code generated by compiling File1.cs. This file also contains metadata table s that describe the types, methods fields, properties, events and so on that are defined by File1.cs. The metadata tables also describe the types, methods and so on that are referenced by File1.cs. The myappln.dll is a separate file. Like File1.netmodule this file includes the IL code generated by compiling File2.cs and also includes similar definition and reference metadata tables. However myappln.dll contains the additional manifest metadata tables, making myappln.dll an assembly. The additional manifest metadata tables describe all of the files that make up the assembly. The manifest metadata tables also include all of the public types exported from myappln.dll and File2.netmodule.

Any client code that consumes the myappln.dll assembly’s types must be built using the /r[eference]:myappln.dll compiler switch. This switch tells the compiler to load the myappln.dll assembly and all of the files listed in its FileDef table when searching for an external type.

The CLR loads assembly files only when a method referencing a type in an unloaded assembly  is called. This means that to run an application, all of the files from a referenced assembly do not need to be present.

Using the Assembly Linker

The Al.exe utility can produce an EXE or a DLL  PE file that contains only a manifest describing the types in other modules. To understand how AL.exe works, lets change the way the myappln.dll assembly is built:

csc /t:module File1.cs

csc /t:module File2.cs

al /out:myappln.dll /t: library File1.netmodule File2.netmodule

In this example, two separate modules, File1.netmodule and File2.netmodule, are created. Neither module is an assembly because they don’t contain manifest metadata tables. Then a third file is produced: myappln.dll which is a small DLL PE file that contains no IL code but has manifest metadata tables indicating that File1.netmodule and File2.netmodule are part of the assembly. The resulting assembly consists of the three files: myappln.dll, File1.netmodule and File2.netmodule. The assembly linker has no way to combine multiple files into a single file.

The AL.exe utility can also produce CUI and GUI PE files using the /t[arget]:exe or /t[arget]:winexe command line switches. You can specify which method in a module should be used as an entry point by adding the /main command-line switch when invoking AL.exe. The following is an example of how to call the Assembly Linker, AL.exe, by using the /main command-line switch.

csc /t:module /r:myappln.dll Program.cs

al /out: Program.exe /t:exe /main: Program.Main Program.netmodule

Here the first line builds the Program.cs file into a Program.netmodule file. The second line produces a small Program.exe PE file that contains the manifest metadata tables. In addition there is a small global function named __EntryPoint that is emitted by AL.exe because of the /main: Program.Main command-line switch. This function, __EntryPoint, contains the following IL code:

.method privatescope static void __EntryPoint$PST06000001() cli managed



As you can see, this code simply calls the Main method contained in the Program type defined in the Program.netmodule file.

Adding Resource Files to an Assembly

When using AL.exe to create an assembly you can add a file as a resource to the assembly by using the /embed[resource] switch. this switch takes a file and embeds the file’s contents into the resulting PE file. The manifest’s ManifestResourceDef table is updated to reflect the existence of the resources.

AL.exe also supports a link[resource] switch, which also takes a file containing resources. However, the /link[resource] switch updates the manifest’s ManifestResourceDef and FileDef tables, indicating that the resource exists and identifying which of the assembly’s files contains it. The resource file is not embedded into the assembly PE file; it remains separate and must be packaged and deployed with the other assembly files.

The C# compiler’s /resource switch embeds the specified resource file into the resulting assembly PE file, updating the ManifestResourceDef table. The compiler’s /linkresource switch adds an entry to the ManifestResourceDef and the FileDef manifest tables to refer to a stand-alone resource file.

You can do this easily by specifying the pathname of a res file with the /win32res switch when using either AL.exe or CSC.exe. In addition you can quickly and easily embed a standard win32 icon resource into an assembly by specifying the pathname of the .ico file with the win32icon switch when using either AL.exe or CSC.exe. Within Visual Studio you can add resource files to your assembly by displaying your project’s properties and then clicking the application tab.

Assembly Version Resource Information

When AL.exe  or CSC.exe produces a PE file assembly, it also embeds into the PE file a standard Win32 version resource. Application code can also acquire and examine this information at runtime by calling System.Diagnostic.FileversionInfo’s static GetVersionInfo method.

Here’s what the code that produced the version information looks like

using System.Reflection;

//FileDescription version version information

[assembly: AssemblyTitle(“MyAppln.dll”)]

// Comments version information:

[assembly: AssemblyCompany(“Wintellect”)]

// ProductName version information

[assembly: AssemblyProduct(“Wintellect ® Jeff’s Type Library”)]

// LegalCopyright version information

[assembly: AssemblyCopyright(“Copyright © wintellect 2010”)]

// LegalTrademask version information:

[assembly:AssemblyTrademark(“JeffTypes is a registered trademark of wintellect”)]

// AssemblyVersion version information

[assembly: AssemblyVersion(“”)]

// FILEVERSION/Fileversion version information:

[assembly: AssemblyinformationalVersion(“”)]

// Set the language field (discussed  later in the “Culture” section)

[assembly: AssemblyCulture(“”)]

The table below shows the Version Resource Fields and Their Corresponding AL.exe Switches and Custom attributes

Version Resource Al.exe Switch Custom Attribute/Comment
FILEVERSION /fileversion System.Reflection.AssemblyFileVersionAttribute
PRODUCTVERSION /productversion System.Reflection.AssemblyInformationalVersionAttribute
FILEFLAGS (none) Always 0
FILEOS (none) Currently always VOS__WINDOWS32
FILETYPE /target Set to VFT_APP if /target:exe or /target:winexe is specified set to VFT_DLL if /target:library is specified
FILESUBTYPE (none) Always set to VFT2_UNKNOWN
AssemblyVersion /version System.Reflection.AssemblyVersionAttribute
Comments /description System.Reflection.AssemblyDescriptionAttribute
CompanyName /company System.Reflection.AssemblyCompanyAttribute
FileDescription /title System.Reflection.AssemblyTitleAttribute
FileVersion /version System.Reflection.AssemblyFileVersionAttribute
InternalName /out Set the name of the output file specified without the extension
LegalCopyright /copyright System.Reflection.AssemblyCopyrightAttribute
LegalTrademarks /trademark System.Reflection.AssemblyTrademarkAttribute
OriginalFileName /out set to the name of the output file (without a path)
PrivateBuild (none) Always blank
ProductName /product System.Reflection.AssemblyProductAttribute
ProductVersion /productversion System.Reflection.AssemblyInformationalVersionAttribute
SpecialBuild (none) Always blank
  • AssemblyFileVersion This version number is stored in the Win32 version resource. This number is for information purposes only; the CLR doesn’t examine this version number in any way.
  • AssemblyinformationalVersion This version number is also stored in the Win32 version resource and again, this number is for information purposes only;
  • AssemblyVersion This version is stored in the AssemblyDef manifest metadata table. The CLR uses this version number when binding to strongly named assemblies. This number is extremely important and is used to uniquely identify an assembly. when starting to develop an assembly, you should set the major , minor, build and revision numbers and shouldn’t change them until you’re ready to being work on the next deployable version of your assembly. When you build an assembly, this version m\number of the referenced assembly is embedded in the AssemblyRef table’ entry. This means that an assembly is tightly bound to a specific version of a referenced assembly.

Simple Application Deployment

Assemblies don’t dictate or require any special means of packaging. The easiest way to package a set of assemblies is simply to copy all of the files directly. Because the assemblies include all of the dependent assembly references and types, the user can just run the application and the runtime will look for referenced assemblies in the application’s directory. No modifications to the registry  are necessary for the application to run. To uninstall the application, just delete all the files.

You can use the options available on the publish tab to cause Visual Studio to produce and MSI file can also install any prerequisite components such as the .NET Framework or Microsoft SQL Server 2008 Express Edition. Finally, the application can automatically check for updates and install them on the user’s machine by taking advantage of ClickOnce technology.

Assemblies deployed to the same directory as the application are called privately deployed assemblies. Privately deployed assemblies can simply be copied to an application’s base directory, and the CLR will load them and execute the code in them. In addition, an application can be uninstalled by simply deleting the assemblies in its directory. This allows simple lookup and restore as well.

This simple install/remove/uninstall scenario is possible because each assembly has metadata indicating which referenced assembly should be loaded, no registry settings are required. An  application always binds to the same type it was built and tested with; the CLR can’t load a different assembly that just happens to provide a type with the same name.

Simple Administrative Control

To allow administrative control over an application a configuration file can be placed in the application’s directory. The setup program would then install this configuration file in the application’s base directory. The CLR interprets the content of this file to alter its policies for locating and loading assembly files.

Using a separate file allows the file to be easily backed up and also allows the administrator to copy the application to another machine – just copy the necessary files and the administrative policy is copied too.

The CLR won’t be able to locate and load these files; running the application will cause a System.IO.FileNotFoundException exception to be thrown. To fix this, the publisher creates an XML configuration file and deploys it to the application base directory. The name of this file must be the name of the application’s main assembly file with a .config extension: program.exe.config for this example. This configuration file should look like this:



<assemblyBinding xmlns=”urn: schema-microsoft-com:asm.v1”>

<probing privatePAth=”AuxFiles” />




Whenever the CLR attempts to locate an assembly file, it always looks in the application’s directory first and if it cant find the file there, it looks in the AuxFiles subdirectory. You can specify multiple semicolon-delimited paths for the probing element’s privatePath attribute. Each path is considered relative to the application’s base directory. You can’t specify an absolute or a relative path identifying a directory that is outside of the application base directory.

The name and location of this XML configuration file is different depending on the application type

  • For executable applications(EXE), the configuration file must be in the application’s base directory, and it must be the name of the EXE file with “config” appended to it.
  • For microsoft ASP.NET Web Form applications, the file must be in the web application’s virtual root directory and is always named web.config

When you install the .NET Framework, it creates a Machine config file. There is one Machine.config file per version of the CLR you have installed on the machine.

The Machine.config file is located in the following directory:


Of course, %SystemRoot% identifies your windows directory (usually C:\WINDOWS), and version is a version number identifying a specific version of the .NET Framework. Settings in the Machine.config file represent default settings that affect all applications running on the machine. An administrator can create a machine-wide policy by modifying the single Machine.config file. However, administrators and users should avoid modifying this file. Plus you want the application’s settings to be backed up and restored, and keeping an application’s settings in the application-specific configuration file enables this.


C# Generics

  1. Introduction
  2. Infrastructure for Generics
  3. Generic Types and Inheritance
  4. Contravariant and Covariant Generic Types
  5. Verifiability and Constraints

C# Generics

Generics is mechanism offered by the common language runtime (CLR) and programming languages that provides one more form of code reuse : algorithm reuse

Microsoft design guidelines that generic parameter variables should either be called T or least start with an uppercase T. The uppercase T stands for type, just as I stands for interface as in IEnumerable.

Generics provide the following big benefits to developers:

– Source code protection : The developer using a generic algorithm doesn’t need to have access to the algorithm’s source code.

– Type safety : When a generic algorithm is used with a specific type, the compiler and the CLR understand this and ensure that only objects compatible with the specified data type are used with the algorithm. Attempting to use an object of an incompatible type will result in either a compiler error or a runtime exception being thrown.

– Cleaner code : The code is easier to maintain, since the compiler enforces type safety, fewer casts are required the code.

– Better Performance : Generic algorithm can be created to work with a specific value type and the CLR no longer has to do any boxing and casts are unnecessary. The CLR doesn’t have to check the type safety of the generated code and this enhances the performance of the algorithm.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
public static class MyApp {
public static void Main() {
private static void ValueTypePerfTest() {
const Int32 count = 10000000;
using (new OperationTimer(“List<Int32>”)) {
List l = new List(Count);
for (Int32 n = 0; n < count; n++) {
l.Add(n) ;
Int32 x = l[n];
l = null; // Make sure this gets GC’d
using (new OperationTimer(“ArrayList of Int32”)) {
ArrayList a = new ArrayList();
for (Int32 n = 0; n < count; n++) {
Int32 x = (Int32) a[n];
a = null; // Make sure this gets GC’d
private static void ReferenceTypePerfTest () {
const Int32 count = 10000000;
using (new OperationTimer(“List<String>”)) {
List<String> l = new List<String>();
for (Int32 n = 0; n < count; n++) {
l.Add(“X”) ;
String x = l[n];
l = null; // Make sure this gets GC’d
using ( new OperationTimer(“ArrayList of String”)) {
ArrayList a = new ArrayList();
for (Int32 n = 0; n < count; n++) {
String x = (String) a[n];
a = null; // Make sure this gets GC’d
// This class is useful for doing operations performance timing
internal sealed class OperationTimer : IDisposable {
private Int64 m_startTime;
private String m_text;
private Int32 m_collectionCount;
public OperationTimer(String text) {
m_text = text;
m_collectionCount = GC.CollectionCount(0) ;
// This should be the last statement in this
// method to keep timing as accurate as possible
m_startTime = Stopwatch.GetTimestamp();
public void Dispose() {
Console.WriteLine(“(0,6:###.00) seconds (GCs={1,3}) {2}”,
(StopWatch.GetTimestamp() – m_startTime) /
(Double) StopWatch.Frequency, GC.CollectionCount(0) –
m_collectionCount, m_text);
private static void PrepareForOperation() {

When I run this program

.20 seconds (GCs = 0) List<Int32>

3.30 seconds (GCs = 45) ArrayList of Int32

.50 seconds (GCs = 6) List<String>

.58 seconds (GCs = 6) ArrayList of String

The output here shows that using the generic List with Int32 type is much faster than using the non-generic ArrayList algorithm with Int32. Also using the value type – Int32 with ArrayList causes a lot of boxing operations to occur which results in 45 GC where as List algorithm requires 0 GC.

So it doesn’t appear that the generic List algorithm is of any benefit here. But it gives a cleaner code and compile time type safety.

Generics inside FCL

Microsoft recommends that developers use the generic collection classes and now discourages use of the non-generic collection classes for several reasons. First, the non-generic collection classes are not generic and so you don’t get the type safety, cleaner code, and better performance that you get when you use generic collection classes. Second the generic classes have a better object model than non-generic classes. For example, fewer methods are virtual, resulting in better performance, and new members have been added to the generic collections to provide new functionality.

The FCL ships with many generic interface definitions so that the benefits of generics can be realized when working with interface as well. The commonly used interfaces are contained in the System.Collections.Generic namespace.

Infrastructure for Generics

Microsoft had to provide the following for Generics to work properly.

– Create new IL instructions that are aware of type arguments

– Modify the format of existing metadata tables so that type names and methods with generic parameters could be expressed.

– Modify the various programming languages to support the new syntax, allowing developers to define and reference generic types and methods

– Modify the compilers to emit the new IL instructions and the modified metadata format.

– Modify the just-in-time(JIT) compiler to process the new type argument aware IL instructions that produce the correct native code.

– Create new reflection members so that developers can query types and members to determine if they have generic parameters. Created new methods using Reflection had to be defined so that developers could create generic type and method definitions at runtime.

– Modify the debugger to show and manipulate generic types, members, fields and local variables.

– Modify the Microsoft VS Intellisense feature to show specific member prototypes when using a generic type or a method with a specific data type.

Open and Closed Types

The CLR creates an internal data structure for each and every type in use by an application. These data structures are called type objects. A type with generic type parameters is still considered a type and the CLR will create an internal type object for each of these. This applies to reference types, value types, interface types and delegate types. A type with generic type parameters is called Open type and the CLR doesn’t allow any instance of an open type to be constructed .

When code references a generic type it can specify a set of generic type arguments. If actual data types are passed in for all of the type arguments, the type is called a closed type, and the CLR does allow instances of a closed type to be constructed.

For e.g.

using System;

using System.Collections;

using System.Collections.Generic;

// A partially specified open type

internal sealed class DictionaryStringKey<TValue> : Dictionary<String, TValue> {


public static class MyApp {

public static void Main() {

Object o = null;

//Dictionary<,> is an open type having 2 new type parameters

Type t = typeof(Dictionary<,>);

// try to create an instance of this type ( fails)

o = CreateInstance(t);


//DictionaryStringKey<,> is an open type having 1 type parameter

t = typeof(DictionaryStringKey<>);

// Try to create an instance of this type fails

o = CreateInstance(t)


// DictionaryStringKey<Guid> is a closed type

t = typeof(DictionaryStringKey<Guid>);

// Try to create an instance of this type succeeds

o = CreateInstance(t)

Console.WriteLine(“Object types=”+o.GetType());


private static Object CreateInstance(Type t) {

Object o = null;

try {

o = Activator.CreateInstance(t);

Console.Write(“Created instance of (0)”,t.ToString());


catch ( ArgumentException e ) {



return 0;



When we execute this code, we get the following output:

Cannot create an instance of System.Collections.Generic.Dictionary 2[TKey, TValue] because Type.ContainsGenericParameters is true.

Cannot create an instance of DictionaryStringKey 1[TValue] because Type.ContainsGenericParameters is true.

Created an instance of DictionaryStringKey `1[System.Guid]

Object Type = DictionaryStringKey `1[System.Guid]

In the output we see that the names end with a backtick (`) followed by a number, it is type’s arity which indicates the number of type parameters required by the type.

Generic Types and Inheritance

A generic type is a type, and it can be derived from any other type. When you use generic type and specify type arguments, you are defining a new type object in the CLR, and the new type object is derived from whatever type generic type was derived from. I.e. List <T> is derived from Object, List<String> and List<Guid> are also derived from Object. Similarly, DictionaryStringKey<TValue> is derived from DictionaryStringKey<String, TValue> , DictionaryStringKey<Guid> is also derived from Dictionary<String, Guid>. Consider an example below

internal class Node {

protected Node m_next;

public Node(Node next) {

m_next = next;



internal sealed class TypedNode<T> : Node {

public T m_data;

public TypedNode(T data) : this(data, null) {


public TypedNode(T data, Node next) : base(next) {

m_data = data;


public override String ToString() {

return m_data.ToString() = (( m_next ! = null) ? m_next.ToString() : String.Empty);



Now the main code will be as follows

private static void DifferentDataLinkedList() {

Node head = new TypedNode<Char>(‘,’);

head = new TypedNode<DateTime>(DateTime.Now, head);

head = new TypedNode<String>(“Today is”, head)’;



Generic Type Identity

C# does offer a way to use simplified syntax to refer to a generic closed type while not affecting type equivalence at all; you can use the good old using directive at the top of your source code file. Here is an example:

using DateTimeList = System.Collections.Generic.List<System.DateTime>;

Using directive is really just defining a symbol called DateTimeList. As the code compiles, the compiler substitutes all occurrences of DateTimeList with System.Collections.Generic.List<System.DateTime>. This just allows developers to use a simplified syntax without affecting the actual meaning of the code, and therefore, type identity and equivalence are maintained. So now when the following line executes the sameType will initialized to true.

Boolean sameType = (typeof(List<DateTime>) == typeof(DateTimeList));

Code Explosion

When a method that uses generic type parameters is JIT-compiled, the CLR takes the method IL, substitutes the specified type arguments, and then creates native code that is specific to that method operating on the specified data types. The CLR keeps generating the native code for every method/type combination. This is referred to as code explosion.

Fortunately, CLR has some optimizations built into it to reduce code explosion. First, if a method is called for a particular type argument, and later the method is called again using the same type argument, the CLR will compile the code for this method/type combination just once. So if assembly uses List<DateTime>, and a completely different assembly also uses List<DateTime>, the CLR will compile the methods for List<DateTime>. This reduces the code explosion. The CLR has another optimization: the CLR considers all reference type arguments to be identical and the code can be shared. For example, the code compiled by the CLR for List<String>’s method can be used for List<Stream>’s methods, since String and Stream are both reference types. In fact, for any reference type, the same code will be used. But if the type argument is a value type, the CLR must produce native code specifically for that value type. The reason is the value types can vary in size.

Generic Interfaces

CLR supports Generic Interface to avoid boxing and loss of compile time type safety. A reference or value type can implement a generic interface by specifying type arguments, or a type can implement a generic interface by leaving the type arguments unspecified.

The definition of a generic interface in the System.Collections.Generic namespace that is part of FCL :

public interface IEnumerator<T> : IDisposable, IEnumerator {

T Current { get; }


Eg of Generic Interface

internal sealed class Triangle : IEnumerator<Point> {

private Point[] m_vertices;

// IEnumerator<Point>’s Current property is of type Point

public Point Current { get {….}}



Now the Generic class that implements Generic Interface

internal sealed class ArrayEnumerator<T> : IEnumerator<T> {

private T[] m_array;

// IEnumerator<T>’s Current property is of type T

public T Current { get {…} }



Generic Delegates

The CLR supports generic delegates to ensure that any type of object can be passed to a callback method in a type-safe way. Furthermore generic delegates allow a value type instance to be passed to a callback method without any boxing. “Delegates,” a delegate is really just a class definition with four methods: a constructor, an invoke method, a BeginInvoke method, and an EndInvoke method. When you define a delegate type that specifies type parameters, the compilers emits the delegate class’s methods and the type parameters are applied to any methods having parameters/return values of the specified type parameter.

For example, if you define a generic delegate like this:

public delegate TReturn CallMe<TReturn, TKey, TValue>(TKey key, TValue value);

The compiler turns that into a class that logically looks like this:

public sealed class CallMe<TReturn, TKey, TValue> : MulticastDelegate {

public CallMe(Object object, IntPtr method);

public virtual TReturn Invoke(TKey key, TValue value);

public virtual TReturn IAsyncResult BeginInvoke(TKey key, TValue value,

AsyncCallback callback, Object object);

public virtual TReturn EndInvoke(IAsyncResult result);


It is recommended that one should use the generic Action and Func delegates that come predefined in the Framework Class Library wherever possible.

Contravariant and Covariant Generic Types

Each of a delegate’s generic type parameters can be cast to a variable of generic delegate type where the generic parameter type differs, A generic type parameter can be of the following:

Invariant : A generic type parameter that cannot be changed.

Contravariant : A generic type parameter that can change from a class to a class derived from it. The contravariant can appear as only input parameters with in keyword

Covariant : A generic type parameter that can change from a class to one of its base classes. In C#, you indicate covariant generic type parameters with the out keyword which can appear only in output positions such as a method’s return type.

public delegate TResult Func<in T, out TResult>(T arg);

In this generic type parameter T is marked with the in keyword making it contravariant; and the generic type parameter TResult is marked with the out keyword, making it covariant .

If I have variable declared as follows:

Func<Object, ArgumentException> fn1 = null;

I can cast it to another Func type, where the generic type parameters are different:

Func<String, Exception> fn2 = fn1; // no explicit cast is required here

Exception e = fn2(“ “);

Here fn1 refers to a function that accepts an Object and returns an ArgumentException. The fn2 variable wants to refer to a method that takes a String and returns an Exception. Since you can pass a String to a method that wants an Object, and since you can take the result of a method that returns an ArgumentException and treat it as an Exception, the code above compiler and is known at compile time to preserve type safety.

Note: Variance is not possible for value types because boxing would be required. Also variance is not allowed on a generic type parameter if an argument of that type is passed to a method using the out or ref keyword. And CLR would throw a following exception if it find this kind of statement :

Invalid variance: They type parameter ‘T’ must be invariantly valid on ‘SomeDelegate<T>.Invoke(ref T)’. ‘T’ is contravariant.”

delegate void SomeDelegate<in T>(ref T t);

When using delegates that take generic arguments and return values, it is recommended to always specify the in and out keywords for contravariance and covariance whenever possible as doing this has no ill effects and enables your delegate to be used in more scenarios.

Here is an example of an interface with a contravariant generic type parameter:

public interface IEnumerator<out T> : IEnumerator {

Boolean MoveNext();

T Current { get; }


Since T is contravariant, it is possible to have the following code compile and run successfully:

// This method accepts an IEnumerable of my reference type

Int32 Count(IEnumerable<Object> collection) {…}


//The call below passes an IEnumerable<String> to count

Int32 c = count(new[] { “Grant” });

for this reason the compiler team forces you to be explicit when declaring a generic type parameter. Then if you attempt to use this type parameter in a context that doesn’t match how you declared it, the compiler issues an error letting you know that you are attempting to break the contract. If you then decide to break the contract by adding in or out on generic type parameters, you should expect to have to modify some of the code sites that were using the out contract.

Generic Methods

When you define a generic class, struct, or interface, any methods defined in these types can refer to a type parameter specified by the type. A type parameter can be used as a method’s parameter, a method’s return value, or as a local variable defined inside the method. However, the CLR also supports the ability for a method to specify its very own type parameters. And these type parameters can also be used for parameters, return values, or local variables.

internal sealed class GenericType<T> {

private T m_value;

public GenericType( T value) { m_value = value; }

public TOutput Converter<TOutput> () {

TOutput result = (TOutput) Convert.ChangeType(m_value, typeof(TOutput));

return result;



In this example, you can see that the GenericType class defines its own type parameter(T), and the Converter method defines its own type parameter(TOutput). This allows a GenericType to be constructed to work with any type. The converter method can convert the object referred to by the m_value field to various types depending on what type argument is passed to it when called. The ability to have type parameters and method parameters allows for phenomenal flexibility.

A reasonably good example of a generic method is the two method

private static void swap<T>(ref T o1, ref T o2) {

T temp = o1;

o1 = o2;

o2 = temp;


Code can now call swap like this

private static void CallingSwap() {

Int32 n1 = 1, n2 =2;

Console.WriteLine(“n1={0}, n2={1}”, n1, n2);

Swap<Int32>(ref n1, ref n2);

Console.WriteLine(“n1={0}, n2={1}”, n1, n2);

String s1 = “Aidan”, s2 = “Grant”;

Console.WriteLine(“s1={0}, s2={1}”, s1, s2);

Swap<String>(ref s1, ref s2);

Console.WriteLine(“s1={0}, s2={1}”, s1, s2);


The variable you pass as an out /ref argument must be the same type as the method’s parameter to avoid a potential type safety exploit.


public static class InterLocked {

public static T Exchange<T>(ref T location1, T value) where T: class;

public static T CompareExchange<T>(

ref T location1, T value, T comparand) where T: class;


Generic Methods and Type Inference

To help improve code creation, readability, and maintainability, the C# compiler offers type inference when calling a generic method. Type inference means that the compiler attempts to determine the type to use automatically when calling a generic method.

Here is some code that demonstrates type inference:

private static void CallingSwapUsingInference() {

Int32 nl = 1, n2 =2;

Swap(ref n1, ref n2);// Calls Swap<Int32>

String s1 = “Aidan”;

Object s2 = “Grant”;

Swap(ref s1, ref s2);// Error, type can’t be inferred


In this code, first call to Swap compiler infers n1 and n2 are Int32 and hence it will invoke Swap with Int32 type parameter. In the second call compiler sees that s1 is String and s2 is Object. Since s1 and s2 are variables of different data types, the compiler can’t accurately infer the type to use for swap’s type argument,and it issues invalid type arguments error for method ‘Swap<T>(ref T, ref T)’ .

Another type is a type that can be defined with multiple methods with one of its methods taking a specific data type and another taking a generic type parameter as shown below in the code

private static void Display(String s) {



private static void Display<T>(T o) {

Display(o.ToString()); //Calls Display(String)


Here are some ways to call the Display method

Display(“Jeff”); // Calls Display(String)

Display(123); // Calls Display<T>(T)

Display<String>(“Adrian”); // Calls Display<T>(T)

The C# compiler always prefers a more explicit match over a generic match, and therefore, it generates a call to the non-generic Display method that takes a String. For the second call, the compiler can’t call the non-generic Display method that takes a String, so it must call the generic Display method. By the way, it is fortunate that the compiler always prefers the more explicit match; if the compiler had preferred the generic method, because the generic display method calls Display again there would have been infinite recursion.

Verifiability and Constraints

A constraint is a way to limit the number of types that can be specified for a generic argument, Limiting the number of types allows you to do more with those types. Here is a new version of the Min method that specifies a constraint:

public static T Min<T o1, To2> where T : IComparable<T> {

if (o1.CompareTo(o2) < 0) return o1;

return o2;


The C# where token tells the compiler that any type specified for T must implement the generic IComparable interface of the same type(T). Because of this constraint, the compiler now allows the method to call the CompareTo method since this method is defined by the IComparable<T> interface.

Now when code references a generic type or method, the compiler is responsible for ensuring that a type argument that meets the constraints is specified.

For e.g.

private static void CallMin() {

Object o1 = “Jeff”, o2 = “Richter”;

Object oMin = Min<Object>(o1, o2); //Error


The compiler issues the error because system.Object doesn’t implement the IComparable<Object> interface. In fact, system.Object doesn’t implement any interfaces at all.

The CLR doesn’t allow overloading based on the type parameter names or constraints you can overload types or methods based only on arity. The following e.g. shows that

// It is OK to define the following types

internal sealed class AType {}

internal sealed class AType <T>{}

internal sealed class AType <T1, T2>{}

//error : conflicts with AType<T> that has no constraints

internal sealed class AType<T> where T: IComparable<T> {}

//Error: conflicts with AType<T1, T2>

internal sealed class AType <T3, T4>{}

internal sealed class AnotherType {

private static void M() {}

private static void M<T>() {}

private static void M<T1, T2>() {}

//Error: conflicts with M<T> that has no constraints

private static void M<T>() where T : IComparable<T> {}


private static void M<T3, T4>() {}


In fact, the overriding method is not allowed to specify any constraints on its type parameters at all. However, it can change the names of the type parameters. similarly, when implementing an interface method, the method must specify the same number of type parameters as the interface method and these type parameters will inherit the constraints specified on them by the interface’s method.


internal class Base {

public virtual void M<T1, T2>()

where T1 : struct

where T2 : class {



internal sealed class Derived : Base {

public override void M<T3, T4>()

where T3 : EventArgs //Error

where T4: class //Error

{ }


Notice that you can change the names of the type parameters as in the example from T1 to T3 and T2 to T4; however you cannot change constraints.

A type parameter can be constrained using a primary constraint, a secondary constraint, and constructor constraint.

Primary Constraint

A primary constraint can be reference type that identifies a class that is not sealed. You cannot specify one of the following special reference types: System.Object, System.Array, System.Delegate, System.MulticastDelegate, System.Valuetype, System.Enum or System.Void

When specifying a reference type constraint, you are promising the compiler that a specified type argument will either be of the same type or of a type derived from the the constant type. For e.g.

internal sealed class PrimaryConstraintOfStream<T> where T : Stream {

public void M(T stream) {

stream.Close(); //OK



In this class definition the type parameter T has a primary constraint of Stream. This tells the compiler that code using PrimaryConstraintOfStream must specify a type argument of Stream or a type derived from stream. If a type parameter doesn’t specify a primary constraint, System.Object is assumed. However, the C# compiler issues an error message if you explicitly specify System.Object in your source code.

There are two special primary constraints: class and struct. The class constraint promises the compiler that a specified type argument will be reference type. Any class type, interface type delegate type or array type satisfies this constraint. For e.g.

internal sealed class PrimaryConstraintOfClass<T> where T : class {

public void M() {

T temp = null; // Allowed because T must be a reference type



In this example setting temp to null is legal because T is known to be a reference type, and all reference type variables can be set to null. If T were unconstrained, the code above would not compile because T could be a value type, and value type variables cannot be set to null.

The struct constraint promises the compiler that a specified type argument will be a value type. Any value type, including enumerations, satisfies this constraint. However, the compiler and the CLR treat any System.Nullable<T> value type as a special type and nullable types do not satisfy this constraint. The reason is because the Nullable<T>type constrains its type parameter to struct, and the CLR wants to prohibit a recursive type such as Nullable<Nullable<T>>


internal sealed class PrimaryConstraintOfStruct<T> where T : struct {

public static T Factory() {

//Allowed because all value types implicitly

// have a public parameterless constructor

return new T();



In this example, newing up a T is legal because T is known to be a value type and all value types implicitly have a public, parameterless constructor. If T were unconstrained, constrained to a reference type or constrained to class, the above code would not compile because some reference types do not have public, parameterless constructors

Secondary Constraint

A type parameter can specify zero or more secondary constraints where a secondary constraint represents an interface type. When specifying an interface type constraint, you are promising the compiler that a specified type argument will be a type argument must specify a type that implements all of the interface constraints

There is another kind of secondary constraint called a type parameter constraint. This kind of constraint is used much less often than interface constraint. It allows a generic type of method to indicate that there must be a relationship between specified type arguments. A type parameter can have zero or more type constraints applied to it. Here is a generic method that demonstrates the use of a type parameter constraint:

private static List<TBase> ConvertIList<T, TBase>(IList<T> list) where T : TBase {

List<TBase> baseList = new List<TBase>(list.count);

for (Int32 index = 0; index < list.Count; index++) {



return baseList;


The convertIList method specifies two types parameters in which the T parameter is constrained by the TBase type parameter. This means that whatever type argument is specified for T, the type argument must be compatible with whatever type arguments is specified for TBase. Here is a method showing some legal and illegal calls to convertIList:

private static void CallingConvertIList(){

//Construct and initialize a List<String> (which implements IList<String>)

IList<String> ls = new List <String>();

ls.Add(“A String”);

//Convert the IList<String> to an IList<Object>

IList<Object> lo = ConvertIList<String, Object>(ls);

//Convert the IList<String> to an IList<IComparable>

IList<IComparable> lc = ConvertIList<String, IComparable>(ls);

//Convert the IList<String> to an IList<IComparable<String>>

IList<IComparable<String>> lcs = ConvertIList<String, IComparable<String>>(ls);

//Convert the IList<String> to an IList<IComparable>

IList<String> ls2 = ConvertIList<String, String>(ls);

//Convert the IList<String> to an IList<Exception>

IList<Exception> le = ConvertIList<String, Exception>(ls); //Error

In the first call to ConvertIList, the compiler ensures that String is compatible with Object. Since String is derived from Object, the first call adheres to the type parameter constraint. In the second call to ConvertIList, the compiler ensures that String is compatible with IComparable. Since String implements the IComparable interface, the second call adheres to the type parameter constraint. In the third call to ConvertIList, the compiler ensures that String is compatible with IComparable<String> Since String implements the IComparable<String> interface, the third call adheres to the type parameter constraint. In the fourth call to ConvertIList, the compiler knows that String is compatible with itself. In the fifth call to ConvertIList, the compiler ensures that string is compatible with Exception. Since String is not compatible with Exception, the fifth call doesn’t adhere to they type parameter constraint, and the compiler issues the following message: “error CS0311: The type string cannot be used as type parameter ‘T’ in the generic type or method ‘Program.ConvertIList<T,TBase>(System.Collections.Generic.IList<T>)’. There is no implicit reference conversion from string to System.Exception”.

Constructor Constraints

A type parameter can specify zero constructor constraints or one constructor constraint. When specifying a constructor constraint, you are promising the compiler that a specified type argument will be a non-abstract type that implements a public, parameterless constructor. Note that the C# compiler considers it an error to specify a constructor constraint with the struct constraint because it is redundant; all value types implicitly offer a public, parameterless constructor.


internal sealed class ConstructorConstraint<T> where T : new() {

public static T Factory() {

// Allowed because all value types implicitly

// have a public, parameterless constructor and because

// the constraint requires that any specified reference

// type also have a public, parameterless constructor

return new T();



In the above example, newing up a T is legal because T is known to be a type that has a public, parameterless constructor. This is certainly true of all value types, and the constructor constraint requires that it be true of any reference type specified as a type argument.

Casting Generic Type

Casting a generic type variable to another type is illegal unless you are casting to a type compatible with a constraint:

private static void CastingGenericTypeVariable1<T>(T obj) {

Int32 x = (Int32) obj; //Error

String s = (String) obj; //Error


The compiler issues an error on both lines above because T could be any type, and there is no guarantee that the casts will succeed. You can modify this code to get it to compile by casting to Object first:

private static void CastingAGenericTypeVariable2<T>(T obj ) {

Int32 x = (Int32) (object) obj; // No Error

String s = (String) (Object) obj; // No Error


If a casting of reference type needs to be done we can use ‘as’ operator. For e.g.

private static void CastingAGenericTypeVariable3<T>(T obj) {

String s = obj as String; // No error


Default value for Generic Type Variable:

Setting a generic type variable to null is illegal unless the generic type is constrained to a reference type.

private static void SettingAGenericTypeVariableToNull<T>() {

T temp = null; //C50403 – Cannot convert null to type parameter T


Since T is unconstrained, it could be a value type, and setting a variable of a value type to null is not possible. If T were constrained to a reference type, setting temp to null would compile and run just fine. C# team felt that it would be useful to give developers the ability to set a variable to a default value. So the C# compiler allows you to use the default keyword to accomplish this

private static void SettingAGenericTypeVariableToDefaultValue<T>(){

T temp = default(T); // OK


The use of the default keyword above tells the C# compiler and the CLR’s JIT compiler to produce code to set temp to null if T is a reference type and to set temp to all-bits-zero if T is a value type.

Comparison of Generic Type variables:

Comparing a generic type variable to null by using the == or != operator is legal regardless of whether the generic type is constrained:

private static void ComparingAGenericTypeVariableWithNull<T>(T obj) {

if(obj == null) { /* Never executes for value type */ }


Since T is unconstrained, it could be a reference type or a value type. If T is a value type, obj can never be null. The C# compiler does not issue an error, instead, it compiles the code just fine. When this method is called using a type argument that is a value type, the JIT compiler sees that the if statement can never be true, and the JIT compiler will not emit the native code for the if test or the code in the braces. If I had used the != operator, the JIT compiler would not emit the code for the if test and it will emit the code inside the if’s braces.

By the way, if T had been constrained to a struct, the compiler would have thrown an error.

Comparing two Generic Type variables

Comparing two variables of the same generic type is illegal if the generic type parameter is not known to be a reference type:

private static void ComparingTwoGenericTypeVariables<T>(T o1, T o2) {

if(o1 == o2) { } //Error


In this example T is unconstrained, and whereas it is legal to compare two reference type variables with one another, it is not legal to compare two value type variables with one another unless the value type overloads the == operator.

By the way, if T had been constrained to a struct, the compiler would have thrown an error.

Avoid Generic Type as Operands

The operators such as +, –, *, and / can’t be applied to variables of a generic type because the compiler doesn’t know the type at compile time. This means that you can’t use any of these operators with variables of a generic type. So it is impossible to write a mathematical algorithm that works on an arbitrary numeric data type.

Digg This
Design Patterns

Design Pattern Part – 5.

Builder Design Pattern falls under the type of creational pattern category.

Just like a house construction follows an ordered process of construction namely

1. Foundation

2. Wall Door & window construction.

3. Roof construction.

Similarly a build pattern follows a ordered process to construct objects. E.g. DB normalization before domain objects and business layer is constructed.

 Figure: – Builder concept

The Builder Design Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.

The Builder pattern requires that you define an interface, which will be used by clients to build complex objects in bits and pieces. Builder pattern is useful when the construction of the object is very complex.

The main objective is to separate the construction of objects and their representations. If we are able to separate the construction and representation, we can then get many representations from the same construction.

Consider we have application where we need the same report to be displayed in either ‘PDF’ or ‘WORD’ format. Figure ‘Request a report’ shows the series of steps to achieve the same. Depending on report type a new report is created, report type is set, headers and footers of the report are set and finally we get the report for display. The construction process is same for both the types of reports but they result in different representations.

We will take the same report problem and try to solve the same using builder patterns. There are three main parts when you want to implement builder patterns.

• Builder: – Builder is responsible for defining the construction process for individual parts. Builder has those individual processes to initialize and configure the product.
• Director: – Director takes those individual processes from the builder and defines the sequence to build the product.
• Product: – Product is the final object which is produced from the builder and director coordination.

First let’s have a look at the builder class hierarchy. We have a abstract class called as ‘ReportBuilder’ from which custom builders like ‘ReportPDF’ builder and ‘ReportWORD’ builder will be built.

Figure ‘Builder classes in actual code’ shows the methods of the classes. To generate report we need to first Create a new report, set the report type (to WORD or PDF), set report headers, set the report footers and finally get the report. We have defined two custom builders one for ‘PDF’ (ReportPDF) and other for ‘WORD’ (ReportWord). These two custom builders define their own process according to the report type.

Figure: – Builder classes in actual code

Now let’s understand how director will work. Class ‘jpDirector’ takes the builder and calls the individual method process in a sequential manner. So director is like a driver who takes all the individual processes and calls them in sequential manner to generate the final product, which is the report in this case. Figure ‘Director in action’ shows how the method ‘MakeReport’ calls the individual process to generate the report product by PDF or WORD.

Figure: – Director in action

The third component in the builder is the product which is nothing but the report class in this case.

Figure: – The report class

Now let’s take a top view of the builder project. Figure ‘Client,builder,director and product’ shows how they work to achieve the builder pattern. Client creates the object of the director class and passes the appropriate builder to initialize the product. Depending on the builder the product is initialized/created and finally sent to the client.

Figure: – Client, builder, director and product 

I hope you enjoyed reading this blog from Design Pattern Series, in my next blog I will be discussing about “Chain of Responsibility” Design Pattern till then happy reading.

Design Patterns

Design Pattern Part – 4

UML Diagram of Bridge Design Pattern
UML Diagram of Bridge Design Pattern

Bridge Pattern

The bridge pattern is a design pattern used in software engineering which is meant to decouple an abstraction from its implementation so that the two can vary independently”.[1] The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.


A bridge is a structural pattern that influences the creation of a class hierarchy by decoupling an abstraction from the implementation. In a bridge however, the abstraction and its implementation can vary independently, and it hides the implementation details from the client.

A simple Illustration of Bridge Design Pattern is ‘Remote has a Car object relationship’. This “has-a” relationship bridge is implemented as Bridge Pattern. Two different parts of the code that is changing except the relationship between them then it is bridge between two changing objects.

Inheritance tree of Car with each node representing the different make of Car, is an example of Bridge pattern.

The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction.

When a class varies often, the features of object-oriented programming become very useful because changes to a program‘s code can be made easily with minimal prior knowledge about the program with the help of bridge pattern.

The bridge pattern can also be thought of as two layers of abstraction.

The following is the sample code Bridge pattern.

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DesignPatterns.Bridge {

public abstract class DataObject


public abstract void Register();

public abstract DataObject Copy();

public abstract void Delete();


public abstract class Repository


public abstract void AddObject(DataObject dataObject);

public abstract void CopyObject(DataObject dataObject);

public abstract void RemoveObject(DataObject dataObject);

public void SaveChanges()


Console.WriteLine(“Changes were saved”);



public class ClientDataObject : DataObject


public override void Register()


Console.WriteLine(“ClientDataObject was registered”);


public override DataObject Copy()


Console.WriteLine(“ClientDataObject was copied”);

return new ClientDataObject();


public override void Delete()


Console.WriteLine(“ClientDataObject was deleted”);



public class ProductDataObject : DataObject


public override void Register()


Console.WriteLine(“ProductDataObject was registered”);


public override DataObject Copy()


Console.WriteLine(“ProductDataObject was copied”);

return new ProductDataObject();


public override void Delete()


Console.WriteLine(“ProductDataObject was deleted”);



public class ProductRepository : Repository


public override void AddObject(DataObject dataObject)


// Do repository specific work



public override void CopyObject(DataObject dataObject)


// Do repository specific work



public override void RemoveObject(DataObject dataObject)


// Do repository specific work





You should use Bridge pattern whenever you Identify that there are operations that do not always need to be implemented in the same way.

You should implement Bridge pattern when following are the requirements of your application:

• Completely hide implementations from clients.

• Avoid binding an implementation to an abstraction directly.

• Change an implementation without even recompiling an abstraction.

• Combine different parts of a system at runtime.

The next blog I will be explaining about the Builder Pattern.

Digg This
Design Patterns

Design Pattern Part–3.

Adapter Pattern

Two different objects have unfriendly interfaces and then we introduce adapter to communicate and interact between them without any changes to the existing interface of the two objects.

Adapter converts the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

An Adapter could indeed have the same interface as the object which it adapts.  In that case, the adapter would add some extra functionality before making the call to the adaptee object.  So, we would not want the exact same interface.  Also, the adapter’s implementation would be different from that of the proxy.

Adapter pattern is like developing mobile software with lot of adapter to run the same software on different mobile brands. Every developer should write documentation about what that adapter method does it do? How to install and configure adapter?

There are four roles within the adapter pattern: client, adapter, adaptee, and the target interface.

The client is a user object that expects a specific interface (or type). We could for the purposes of simplicity state that the client is callee on a type that implements a specific interface. As another example the client may need to concert with a type later on that has implemented a specific interface.

The Adapter wraps the adaptee up and implements the interface the client expects. The adapter sometimes delegates its work to the adaptee.

An adaptee is the type that we want to use with the new code but we can’t because it doesn’t adhere to expected behavior that the client expects.

Finally the target interface is the name given to the interface that the client expects.

Let us illustrate the above mentioned  terminology with the help of a simple example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPatterns.Adapter {
public abstract class Connector     {
public abstract void ReadData();
public class DatabaseUtil
      public void QueryForUpdates()
          Console.WriteLine("Updates queried from DB.");
public class DatabaseConnector : Connector
          public override void ReadData()
         var dbUtil = new DatabaseUtil();
     public class TradingDataImporter
         public void ImportData(Connector connector)
UML Diagram of Adapter Design Pattern
UML Diagram of Adapter Design Pattern

To summarize, we have the following options when matching adapter and adaptee interfaces:

Adapter interface and adaptee interface have same signature
Many examples of the Adapter pattern operate at this level and are not illustrative or helpful in explaining its real power. Beware of them.
Adapter interface has fewer parameters than adaptee interface
The adapter calls the adaptee with some dummy input.
Adapter interface has more parameters than adaptee interface
The adapter adds the missing functionality, making it half an adapter and half a component in its own right.
Adapter interface has other types than adaptee interface
The adapter performs some type conversion (casting).

You should use Adapter pattern when you need to implement

  • A domain-specific interface.
  • A class to connect to with a mismatching interface.
  • a reusable class to cooperate with yet-to-be-built classes.
  • the modification of names of methods as called and as implemented.
  • different sets of methods for different purposes.

In the Next blog I will be explaining about the Bridge pattern. By that time read the blog and send me the feedback.

Digg This
Design Patterns

Design Patterns Part – 2

Abstract Factory

A factory class helps us to centralize the creation of classes and types. Abstract factory helps us to bring uniformity between related factory patterns which leads more simplified interface for the client. Abstract factory expands on the basic factory pattern. Abstract factory helps us to unite similar factory pattern classes in to one unified interface. So basically all the common factory patterns now inherit from a common abstract factory class which unifies them in a common class.

In the Implementation phase,Authors discuss about the idea of defining extensible factories. An Abstract Factory is composed of Factory Methods, and each Factory Method has only one signature. Abstract Factory class provides an interface for creating families of related or dependent objects without specifying their concrete classes. We would have to specify different concrete factory subclasses in order to create an object in multiple ways.

Figure: – Abstract factory unifies related factory patterns

Now that we know the basic lets try to understand the details of how abstract factory patterns are actually implemented. As said previously we have the factory pattern classes (factory1 and factory2) tied up to a common abstract factory (Abstract Factory Interface) via inheritance. Factory classes stand on the top of concrete classes which are again derived from common interface.

Figure: – Implementation of abstract factory

For instance in figure ‘Implementation of abstract factory’ both the concrete classes ‘product1’ and ‘product2’ inherits from one interface i.e. ‘common’. The client who wants to use the concrete class will only interact with the abstract factory and the common interface from which the concrete classes inherit.

Now let’s have a look at how we can practically implement abstract factory in actual code. We have scenario where we have UI creational activities for textboxes and buttons through their own centralized factory classes ‘jpFactoryButton’ and ‘jpFactoryText’. Both these classes inherit from common interface ‘InterfaceRender’.

Figure: – Example for abstract factory

Both the factories ‘jpFactoryButton’ and ‘jpFactoryText’ inherits from the common factory ‘jpAbstractFactory’. Figure ‘Example for AbstractFactory’ shows how these classes are arranged and the client code for the same. One of the important points to be noted about the client code is that it does not interact with the concrete classes. For object creation it uses the abstract factory ( jpAbstractFactory ) and for calling the concrete class implementation it calls the methods via the interface ‘InterfaceRender’. So the ‘jpAbstractFactory’ class provides a common interface for both factories ‘jpFactoryButton’ and ‘jpFactoryText’.

We will just run through the sample code for abstract factory. Below code snippet ‘Abstract factory and factory code snippet’ shows how the factory pattern classes inherit from abstract factory.

Figure: – Abstract factory and factory code snippet

Figure: – Common interface for concrete classes

Figure ‘Common Interface for concrete classes’ how the concrete classes inherits from a common interface ‘InterFaceRender’ which enforces the method ‘render’ in all the concrete classes.

The final thing is the client code which uses the interface ‘InterfaceRender’ and abstract factory ‘jpAbstractFactory’ to call and create the objects. One of the important points about the code is that it is completely isolated from the concrete classes. Due to this any changes in concrete classes like adding and removing concrete classes does not need client level changes.

Figure: – Client, interface and abstract factory

The Abstract Factory is applied when Pattern Factory of factories are to be dynamically customizable. Abstract class of factory are implemented when different types of factories are required. e.g. factory class to create controls for individual OS.

Abstract Factory entities should  create objects at the time of creation of objects not at the time of factory creation or not during the execution of factory constructor. Sample code shows how factories are created dynamically not at abstract factory instantiation time.

Public abstract class connectionFactory {



SecureFactory extends connectionFactory {

connectionFactory create(String type) {

if (type.equals(‘Oracle’)

return new OracleConnection();


return new SQLServer();

else return new MySQL();



The next blog in the series I will be explaining about Adapter Design Pattern. Please send me the feedback on this blog so that I can improve the future blog contents.

Digg This