Friday, October 30, 2009

The .NET Framework


· The .NET Framework
o Detail knowledge on CLR
§ Memory Management / Garbage Collection
§ Thread Management
§ Exception Handling
§ Security
o CTS
o JIT
o Managed and Unmanaged code
o Class Libraries
§ Framework Class Libraries (FCL)
§ Base Class Libraries (BCL)
o MSIL
o Versions of .Net Frameworks
· C# Fundamentals
o C# compiler
o Data Types
§ Value Types
· Predefined Value Types
· Nullable Types
§ Reference Types
§ User-defined Types
§ Anonymous Types
§ Type Conversion
o Flow Control
o Looping
o Operators
o Preprocessor Directives
· Classes and Objects
o Classes
§ Defining a Class
§ Using Partial Classes
§ Anonymous Types (C# 3.0)
§ Instance Members
§ Static Members
§ Access modifiers
§ Function Members
· Methods
o this keyword
· Properties (Read only and write only properties)
· Partial Methods
§ Constructors
· Constructor Chaining
· Static Constructors
· Copy Constructor
§ Destructors
§ Static Classes
o System.Object Class
§ Testing For Equality
§ Implementing Equals
§ ToString() Method
§ Attributes
· Custom Attributes
o Structures
· Interfaces
o Defining an Interface
o Implementing an Interface
o Implementing Multiple Interfaces
o Extending Interfaces
o Interface Casting
o The is and as operators
o Overriding Interface Implementations
· Inheritance
o Understanding Inheritance in C#
o Implementation inheritance
o Interface inheritance
o Explicit Interface Member Implementation
· Delegates and Events
· Strings and Regular Expressions
· Generics
o Understanding Generics
o Generics and the .NET framework Class Library
o Using the LinkedList Generic Class
o System.Collections.ObjectModel
· Threading
o Need for multithreading
o Thread Synchronization
o Thread Safety in Windows Forms
· Files and Streams
o Working with Files and Directories
o The Stream Class
o Cryptography
o Compressions for Stream.Objects
o Serialization
· Exception Handling
o Handling Exceptions
o Creating Custom Exceptions
· Arrays and Collections
· Language Integrated Query (LINQ)
o LINQ Architecture
o LINQ to Objects
o LINQ to DataSet
o LINQ to XML
o LINQ to SQL
· Assemblies and Versioning
o Assemblies
o Private versus Shared Assemblies

1. The .NET Framework
The Microsoft .Net Framework is a platform that provides tools and technologies to build Networked Applications, Distributed Web Services and Web Applications. The .Net Framework provides the necessary compile time and run-time foundation to build and run any language that conforms to the Common Language Specification (CLS).The main two components of .Net Framework are Common Language Runtime (CLR) and .Net Framework Class Library (FCL).
1.1 Detail knowledge on CLR
The Common Language Runtime (CLR) is the runtime environment of the .Net Framework. That executes and manages all running code like a Virtual Machine.
CLR is a core component of Microsoft's .NET initiative. Compilers and tools expose the runtime's functionality and enable you to write code.
The benefit of this is managed execution environment.
Code that you develop with a language compiler that targets the runtime is called managed code, it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.
It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. The CLR runs a form of bytecode called the Common Intermediate Language (CIL, previously known as MSIL -- Microsoft Intermediate Language).
Developers using the CLR write code in a language such as C# or VB.NET. At compile time, a .NET compiler converts such code into CIL code. At runtime, the CLR's just-in-time compiler converts the CIL code into code native to the operating system. Alternatively, the CIL code can be compiled to native code in a separate step prior to runtime. This speeds up all later runs of the software as the CIL-to-native compilation is no longer necessary.
§ Memory Management / Garbage Collection
Memory management is the act of managing computer memory. This involves providing ways to allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed. The management of main memory is critical to the computer system.
Virtual memory systems separate the memory addresses used by a process from actual physical addresses, allowing separation of processes and increasing the effectively available amount of RAM using disk swapping. The quality of the virtual memory manager can have a big impact on overall system performance.
Garbage collection is the automated allocation, and deallocation of computer memory resources for a program. This is generally implemented at the programming language level and is in opposition to manual memory management, the explicit allocation and deallocation of computer memory resources.
Garbage Collection
In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that are no longer in use by the application. Garbage collection was invented by John McCarthy around 1959 to solve the problems of manual memory management in Lisp.
Garbage collection is often portrayed as the opposite of manual memory management, which requires the programmer to specify which objects to de allocate and return to the memory system. However, many systems use a combination of the two approaches, and there are other techniques being studied (such as region inference) to solve the same fundamental problem.
The basic principles of garbage collection are
1. Find data objects in a program that cannot be accessed in the future
2. Reclaim the resources used by those objects.
Garbage collection frees the programmer from having to worry about releasing objects that are no longer needed, which can otherwise consume a significant amount of design effort. It also aids programmers in their efforts to make programs more stable, because it prevents several classes of runtime errors.
Many computer languages require garbage collection, either as part of the language specification (e.g., Java, C#, and most scripting languages) or effectively for practical implementation (e.g., formal languages like lambda calculus); these are said to be garbage collected languages. Other languages were designed for use with manual memory management, but have garbage collected implementations available (e.g., C, C++). Some languages, like Ada, Modula-3, and C++/CLI allow both garbage collection and manual memory management to co-exist in the same application by using separate heaps for collected and manually managed objects; others, like D, are garbage collected but allow the user to manually delete objects and also entirely disable garbage collection when speed is required. In any case, it is far easier to implement garbage collection as part of the language's compiler and runtime system, but post hoc GC systems exist, including ones that do not require recompilation. The garbage collector will almost always be closely integrated with the memory allocator.
Benefits
Garbage collection frees the programmer from manually dealing with memory allocation and deallocation. As a result, certain categories of bugs are eliminated or substantially reduced:
* Dangling pointer bugs, which occur when a piece of memory is freed while there are still pointers to it, and one of those pointers is used.
* Double free bugs, which occur when the program attempts to free a region of memory that is already free.
* Certain kinds of memory leaks, in which a program fails to free memory that is no longer referenced by any variable, leading, over time, to memory exhaustion.
Researchers draw a distinction between "physical" and "logical" memory leaks. In a physical memory leak, the last pointer to a region of allocated memory is removed, but the memory is not freed. In a logical memory leak, a region of memory is still referenced by a pointer, but is never actually used. Garbage collectors generally can do nothing about logical memory leaks. Novice programmers sometimes believe that garbage collection makes memory leaks impossible, not realizing that logical leaks are still possible.
In languages that provide dynamic allocation, garbage collection is crucial to memory safety and often to the associated property of type safety. This in turn improves the security of the language by preventing a wide class of security vulnerabilities based on over-writing memory in unexpected ways.
Disadvantages
Typically, garbage collection has four main disadvantages.
* Garbage collection is a process that consumes finite computing resources in deciding what memory is to be freed and when whereas manual memory management consumes only the minimum required. So the penalty for the convenience of not having to perform manual memory management is overhead leading to decreased algorithmic efficiency. Clearly, if memory is manually released the instant it is no longer required, it will always be the most efficient method since it will then be immediately available for re-allocation by some other process and will require zero decisions to be made (thus reducing overall memory requirements and elapse time).
* The point when the garbage is actually collected (removed) can be unpredictable, leading to small delays scattered through a session. This can be prohibitive in real-time environments such as device drivers or transaction processing.
* use of recursion delays automatic memory release of the stack until at least the final call has completed causing increased memory requirements.
* Semantic garbage detection will forever remain an insoluble problem for any automatic process due to the halting problem (see Reachability of an object below)
Memory management systems on multi-tasking operating systems usually deal with the following issues.
Relocation
In systems with virtual memory, programs in memory must be able to reside in different parts of the memory at different times. This is because when the program is swapped back into memory after being swapped out for a while it can not always be placed in the same location. The virtual memory management unit must also deal with concurrency. Memory management in the operating system should therefore be able to relocate programs in memory and handle memory references in the code of the program so that they always point to the right location in memory.
Protection
Processes should not be able to reference the memory for another process without permission. This is called memory protection, and prevents malicious or malfunctioning code in one program from interfering with the operation of other running programs.
Sharing
Even though the memory for different processes is normally protected from each other, different processes sometimes need to be able to share information and therefore access the same part of memory. Shared memory is one of the fastest techniques for Inter-process communication.
Logical organization
Programs are often organized in modules. Some of these modules could be shared between different programs, some are read only and some contain data that can be modified. The memory management is responsible for handling this logical organization that is different from the physical linear address space. One way to arrange this organization is segmentation.sfggehehhe
Physical organization
Memory is usually divided into fast primary storage and slow secondary storage. Memory management in the operating system handles moving information between these two levels of memory.
Memory compaction
The technique of relocating all occupied areas of memory to one end of the memory so as to get one large block of free memory space is called compaction.
Memory can be compacted under the following conditions:
1. as soon as a job terminates.
2. When a new job cannot be loaded into memory due to fragmentation.
3. at fixed time intervals.
§ Thread Management
In computer science, a thread of execution results from a fork of a computer program into two or more concurrently running tasks. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process. Multiple threads can exist within the same process and share resources such as memory, while different processes do not share these resources.
On a single processor, multithreading generally occurs by time-division multiplexing (as in multitasking): the processor switches between different threads. This context switching generally happens frequently enough that the user perceives the threads or tasks as running at the same time. On a multiprocessor or multi-core system, the threads or tasks will generally run at the same time, with each processor or core running a particular thread or task. Support for threads in programming languages varies: a number of languages simply do not support having more than one execution context inside the same program executing at the same time. Examples of such languages include Python, and OCaml, because the parallel support of their runtime support is limited by the use of a central lock, called "Global Interpreter Lock" in Python, "master lock" in Ocaml. Other languages may be limited because they use threads that are user threads, which are not visible to the kernel, and thus cannot be scheduled to run concurrently. On the other hand, kernel threads, which are visible to the kernel, can run concurrently.
Many modern operating systems directly support both time-sliced and multiprocessor threading with a process scheduler. The kernel of an operating system allows programmers to manipulate threads via the system call interface. Some implementations are called a kernel thread, whereas a lightweight process (LWP) is a specific type of kernel thread that shares the same state and information.
Programs can have user-space threads when threading with timers, signals, or other methods to interrupt their own execution, performing a sort of ad-hoc time-slicing.
§ Exception Handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution.
Unlike signals and event handlers that are part of the normal program flow, exceptions are typically used to signal that something went wrong (e.g. a division by zero occurred or a required file was not found). Exceptions are raised or thrown (initiated) by either the hardware or the program itself by using a special command.
Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.
C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any cleanup process.
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.
But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.
Since there is no exception handling catch block, the execution will get terminated.
By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.
In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as follows.
Standard Exceptions
There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc.
The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.
* System.OutOfMemoryException
* System.NullReferenceException
* Syste.InvalidCastException
* Syste.ArrayTypeMismatchException
* System.IndexOutOfRangeException
* System.ArithmeticException
* System.DevideByZeroException
* System.OverFlowException
Exception Types - There are a number of exception classes provided by C#, all of which inherit from the System.Exception class. Following are some common exception classes.
Exception Class
Cause
SystemException
A failed run-time check;used as a base class for other.
AccessException
Failure to access a type member, such as a method or field.
ArgumentException
An argument to a method was invalid.
ArgumentNullException
A null argument was passed to a method that doesn't accept it.
ArgumentOutOfRangeException
Argument value is out of range.
ArithmeticException
Arithmetic over - or underflow has occurred.
ArrayTypeMismatchException
Attempt to store the wrong type of object in an array.
BadImageFormatException
Image is in the wrong format.
CoreException
Base class for exceptions thrown by the runtime.
DivideByZeroException
An attempt was made to divide by zero.
FormatException
The format of an argument is wrong.
IndexOutOfRangeException
An array index is out of bounds.
InvalidCastExpression
An attempt was made to cast to an invalid class.
InvalidOperationException
A method was called at an invalid time.
MissingMemberException
An invalid version of a DLL was accessed.
NotFiniteNumberException
A number is not valid.
NotSupportedException
Indicates sthat a method is not implemented by a class.
NullReferenceException
Attempt to use an unassigned reference.
OutOfMemoryException
Not enough memory to continue execution.
StackOverflowException
A stack has overflown.
§ Security
.NET has its own security mechanism with two general features: Code Access Security (CAS), and validation and verification. Code Access Security is based on evidence that is associated with a specific assembly. Typically the evidence is the source of the assembly (whether it is installed on the local machine or has been downloaded from the intranet or Internet). Code Access Security uses evidence to determine the permissions granted to the code. Other code can demand that calling code is granted a specified permission. The demand causes the CLR to perform a call stack walk: every assembly of each method in the call stack is checked for the required permission; if any assembly is not granted the permission a security exception is thrown.
When an assembly is loaded the CLR performs various tests. Two such tests are validation and verification. During validation the CLR checks that the assembly contains valid metadata and CIL(Common Intermediate Language), and whether the internal tables are correct. Verification is not so exact. The verification mechanism checks to see if the code does anything that is 'unsafe'. The algorithm used is quite conservative; hence occasionally code that is 'safe' does not pass. Unsafe code will only be executed if the assembly has the 'skip verification' permission, which generally means code that is installed on the local machine.
.NET Framework uses appdomains as a mechanism for isolating code running in a process. Appdomains can be created and code loaded into or unloaded from them independent of other appdomains. This helps increase the fault tolerance of the application, as faults or crashes in one appdomain do not affect rest of the application. Appdomains can also be configured independently with different security privileges. This can help increase the security of the application by isolating potentially unsafe code. The developer, however, has to split the application into subdomains; it is not done by the CLR.
o Detail knowledge on CTS (Common Type System)
As .Net Framework is language independent and support over 20 different programming languages, many programmers will write data types in their own programming language.
For example, an integer variable in C# is written as int, whereas in Visual Basic it is written as integer. Therefore in .Net Framework you have single class called System.Int32 to interpret these variables. Similarly, for the ArrayList data type .Net Framework has a common type called System.Collections.ArrayList. In .Net Framework, System.Object is the common base type from where all the other types are derived.
This system is called Common Type System. The types in .NET Framework are the base on which .NET applications, components, and controls are built. Common Type System in .Net Framework defines how data types are going to be declared and managed in runtime. The Common Type System performs the following functions.
• Automatically adapts itself in a framework that enables integration of multiple languages, type safety, and high performance code execution.
• Provides an object-oriented model.
• Standardizes the conventions that all the languages must follow.
• Invokes security checks.
• Encapsulates data structures.
There are two general types of categories in .Net Framework that Common Type System support. They are value types and reference types. Value types contain data and are user-defined or built-in. they are placed in a stack or in order in a structure. Reference types store a reference of the value’s memory address. They are allocated in a heap structure. You can determine the type of a reference by the values of self-describing types. Reference types can be categorized into self-describing types, pointer types, or interface types.
There are many other types that can be defined under Value types and Reference types. In .Net Framework, the System namespace is the root for all the data types. This namespace consists of classes such as Object, Byte, String, and Int32 that represents base data types. These base data types are used by all applications. During runtime a type name can be classified into two: the assembly name and the type’s name within the assembly. The runtime in .Net Framework uses assemblies to find and load types.
o Detail knowledge on JIT
The high level programming languages that need to be compiled require a runtime, so that the architecture on which the language runs is provided with details on how to execute its code. All the programming languages use its corresponding runtime to run the application. For example, to run an application developed using Visual Basic, the computer on which the application will be run must be installed with the Visual Basic runtime. The Visual Basic runtime can run only the applications developed with Visual Basic and not the ones developed with any other programming language like Java.
In the .NET Framework, all the Microsoft .NET languages use a common language runtime, which solves the problem of installing separate runtime for each of the programming languages. Microsoft .NET Common Language Runtime installed on a computer can run any language that is Microsoft .NET compatible.
The main advantage of the .NET Framework is the interoperability between different languages. As all the Microsoft .NET languages share the same common runtime language, they all work well together. For example, you can use an object written in C# from Visual Basic.NET. The same applies for all the other Microsoft .NET languages.
When you compile a Microsoft.NET language, the complier generates code written in the Microsoft Intermediate Language (MSIL). MSIL is a set of instructions that can quickly be translated into native code.
A Microsoft.NET application can be run only after the MSIL code is translated into native machine code. In .NET Framework, the intermediate language is complied "just in time" (JIT) into native code when the application or component is run instead of compiling the application at development time. The Microsoft.NET runtime consists of two JIT compilers. They are standard JIT compiler and the EconoJIT compiler. The EconoJIT compiler compiles faster than the standard JIT compiler, but the code it produces is not as optimized as the code obtained from the standard JIT compiler.
o Detail knowledge on Managed and Unmanaged code
Managed Code
Code that you develop with a language compiler, that is targets the common language runtime, is called managed code. Managed code must supply the metadata necessary for the runtime to provide services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on Microsoft intermediate language (MSIL) executes as managed code.
Un-Managed Code
Code that is created without regard for the conventions and requirements of the common language runtime. Unmanaged code executes in the common language runtime environment with minimal services (for example, no garbage collection, limited debugging, and so on).
Programs in any programming language could, in principle, be compiled into either managed or unmanaged code. In practice, however, each programming language is typically compiled into one type. For example, the Java programming language is almost always compiled into managed code, although there are Java compilers that can generate unmanaged code (such as GNU Compiler for Java) likewise for the Python language. By contrast, Microsoft's Visual C++ development environment can produce both managed code (running under the .NET CLR) or unmanaged code, running under the older MFC framework. (Microsoft Foundation Class Library)
There are many historical examples of managed code running on a virtual machine, such as UCSD Pascal utilizing p-code. Java popularized this approach with its Bytecode executed by the Java Virtual Machine. Microsoft uses managed code in its CLR virtual machine in the .NET Framework, or another similar virtual machine.
Definitions for managed code:
1. Code that is executed by the CLR. Managed code provides information (i.e., metadata) to allow the CLR to locate methods encoded in assembly modules, store and retrieve security information, handle exceptions, and walk the program stack. Managed code can access both managed data and unmanaged data. Managed data—Memory that is allocated and released by the CLR using Garbage Collection. Managed data can only be accessed by managed code
2.Code that targets the common language runtime, the foundation of the .NET Framework, is known as managed code; code that does not target the common language runtime is known as unmanaged code. You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety in the code. The concept of code management is a fundamental principle of the runtime.
3.Managed code supplies the metadata necessary for the CLR to provide services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on IL executes as managed code.
4.Code that executes under the CLI execution environment. Managed code uses the execution environment for memory management, object lifetime, and the basic type-system, among other fundamental services.
o Class Libraries
The .NET Framework class library is a library of classes, interfaces, and value types that are included in the Windows Software Development Kit (SDK). This library provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built.
The .NET Framework includes two main components: the common language runtime and the .NET Framework class library. The .NET Framework class library is a collection of reusable types that are tightly integrated with the common language runtime. The class library is object oriented, easy to use, and accelerates your development. For example, the .NET Framework collection classes implement a set of APIs that you can use to develop your own collection classes. The .NET Framework class library enables you to accomplish a range of common programming tasks such as string manipulation, data collection, database connectivity, and file access. You can also use this library to develop console applications, Windows Forms, ASP.NET applications, XML Web services, and Windows services. A classic example is the Web Forms classes. They simplify form development in ASP.NET development projects.
§ Framework Class Libraries (FCL)
The .Net Framework Class Library (FCL) is a huge collection of language-independent and type-safe reusable classes. The .Net Framework Class Libraries (FCL) is arranged into a logical grouping according to their functionality and usability is called Namespaces. In the following sections describes how to .Net Framework manages the code in compile time and run time .
The .Net Framework class library (FCL) provides the core functionality of .Net Framework architecture. The .Net Framework Class Library (FCL) includes a huge collection of reusable classes, interfaces, and value types that expedite and optimize the development process and provide access to system functionality.
The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into Namespaces. Namespaces is a logical grouping of types for the purpose of identification. Framework class library (FCL) provides the consistent base types that are used across all .NET enabled languages. The Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root for types in the .NET Framework. The .Net Framework class library (FCL) classes are managed classes that provide access to System Services. The .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Moreover, third-party components can integrate with the classes in the .NET Framework.
BCL (Base Class Libraries) is a part of FCL and provide the most fundamental functionality, which includes classes in namespaces System, System.CodeDom, System.Collections, System.Diagnostics, System.Globalization, System.IO, System.Resources, System.Text, and System.Text.RegularExpressions.
§ Base Class Libraries (BCL)
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 would be 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. FCL forms the main set with BCL acting as the subset.
Standardized namespaces
System - String, DateTime, Boolean
System.Diagnostics - event logging, performance counters, tracing, and interaction with system processes.
System.Globalization - Culture-related information, including the language, the country/region
System.IO - read from and write to different streams, such as files or other data streams.
System.Net - used on networks HTTP, FTP, and SMTP, SSL.
System.Reflection -It exposes the API to access the Reflective programming capabilities of CLR.
System.Runtime -manage the runtime behavior of an application or the CLR. writing distributed applications, and serializing objects into binary or SOAP.
System.Security - runtime security system. It provides services such as cryptography.
System.Text -various encodings, regular expressions
System.Threading -facilitate multithreaded programming.
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.
System.CodeDom
System.ComponentModel
System.Configuration
System.Data
System.Deployment
System.DirectoryServices
System.Drawing
System.Management
System.Media
System.Messaging
System.Linq
System.Linq.Expressions
System.Resources
System.ServiceProcess
System.Timers
System.Transactions
o MSIL
Common Language Infrastructure, the bytecode is now officially known as CIL.
Common Intermediate Language (CIL) formerly called Microsoft Intermediate Language or MSIL is the lowest-level human-readable programming language in the Common Language Infrastructure and in the .NET Framework. Languages which target the .NET Framework compile to CIL, which is assembled into bytecode. CIL is an object-oriented assembly language, and is entirely stack-based. It is executed by a virtual machine.
During compilation of .NET programming languages, the source code is translated into CIL code rather than platform or processor-specific object code. CIL is a CPU- and platform-independent instruction set that can be executed in any environment supporting the .NET framework. CIL code is verified for safety during runtime, providing better security and reliability than natively compiled binaries.
Microsoft Intermediate Language (MSIL) is the assembly language output by .NET compilers—C#, VB .NET, etc.
Learning MSIL affords the programer the opportunity to understand things that are normally hidden while working in C# or VB NET. Although we seldom—if ever—need to write programs directly in MSIL, there are difficult cases when it can be both enlightening and useful to examine the MSIL code in ILDasm to see what is happening behind the curtain.
The Intermediate Language Assembler (ilasm) that ships with the .NET Framework SDK allows programmers to view MSIL code in human-readable format. Using this utility, the MSIL code of any .NET executable file—.DLL, .EXE—can be inspected.
The Intermediate Language Disassembler (ildasm) disassembles MSIL code back into assembly language source code; so, it can be viewed or modified.
o Versions of .Net Frameworks
Version
Version Number
Release Date
Visual Studio
Default in Windows
1.0.3705.0
2002-02-13
Visual Studio .NET

1.1.4322.573
2003-04-24
Visual Studio .NET 2003
Windows Server 2003
2.0.50727.42
2005-11-07
Visual Studio 2005

3.0.4506.30
2006-11-06

Windows Vista, Windows Server 2008
3.5.21022.8
2007-11-19
Visual Studio 2008
Windows 7, Windows Server 2008 R2

2009-05-20
Visual Studio 2010

.NET Framework 1.0
This is the first release of the .NET Framework, released on 13 February 2002 and available for Windows 98, Me, NT 4.0, 2000, and XP. Mainstream support by Microsoft for this version ended 10 July 2007, and extended support ended 14 July 2009.
.NET Framework 1.1
This is the first major .NET Framework upgrade. It is available on its own as a redistributable package or in a software development kit, and was published on 3 April 2003. It is also part of the second release of Microsoft Visual Studio .NET (released as Visual Studio .NET 2003). This is the first version of the .NET Framework to be included as part of the Windows operating system, shipping with Windows Server 2003. Mainstream support for .NET Framework 1.1 ended on 14 October 2008, and extended support ends on 8 October 2013. Since .NET 1.1 is a component of Windows Server 2003, extended support for .NET 1.1 on Server 2003 will run out with that of the OS - currently 14 July 2015.
Changes in 1.1 on comparison with 1.0
* Built-in support for mobile ASP.NET controls. Previously available as an add-on for .NET Framework, now part of the framework.
* Security changes - enable Windows Forms assemblies to execute in a semi-trusted manner from the Internet, and enable Code Access Security in ASP.NET applications.
* Built-in support for ODBC and Oracle databases. Previously available as an add-on for .NET Framework 1.0, now part of the framework.
* .NET Compact Framework - a version of the .NET Framework for small devices.
* Internet Protocol version 6 (IPv6) support.
* Numerous API changes.
.NET Framework 2.0
Released with Visual Studio 2005, Microsoft SQL Server 2005, and BizTalk 2006.
* The 2.0 Redistributable Package can be downloaded for free from Microsoft, and was published on 22 January 2006.
* It is included as part of Visual Studio 2005 and Microsoft SQL Server 2005.
* Version 2.0 without any Service Pack is the last version with support for Windows 98 and Windows Me. Version 2.0 with Service Pack 2 is the last version with official support for Windows 2000 although there have been some unofficial workarounds published online to use a subset of the functionality from Version 3.5 in Windows 2000. Version 2.0 with Service Pack 2 requires Windows 2000 with SP4 plus KB835732 or KB891861 update, Windows XP with SP2 or later and Windows Installer 3.1 (KB893803-v2).
* It shipped with Windows Server 2003 R2 (not installed by default).
Changes in 2.0 in comparison with 1.1
* Numerous API changes.
* A new hosting API for native applications wishing to host an instance of the .NET runtime. The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more (detailed reference). It was initially developed to efficiently host the runtime in Microsoft SQL Server, which implements its own scheduler and memory manager.
* Full 64-bit support for both the x64 and the IA64 hardware platforms.
* Language support for generics built directly into the .NET CLR.
* Many additional and improved ASP.NET web controls.
* New data controls with declarative data binding.
* New personalization features for ASP.NET, such as support for themes, skins and webparts.
* .NET Micro Framework - a version of the .NET Framework related to the Smart Personal Objects Technology initiative.
* Partial classes
* Anonymous methods
* Data Tables
.NET Framework 3.0
.NET Framework 3.0, formerly called WinFX, was released on 21 November 2006. It includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems. It is also available for Windows XP SP2 and Windows Server 2003 as a download. There are no major architectural changes included with this release; .NET Framework 3.0 uses the Common Language Runtime of .NET Framework 2.0. Unlike the previous major .NET releases there was no .NET Compact Framework release made as a counterpart of this version.
.NET Framework 3.0 consists of four major new components:
* Windows Presentation Foundation (WPF), formerly code-named Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies. See WPF SDK for developer articles and documentation on WPF.
* Windows Communication Foundation (WCF), formerly code-named Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
* Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
* Windows CardSpace, formerly code-named InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website.
.NET Framework 3.5
Version 3.5 of the .NET Framework was released on 19 November 2007, but it is not included with Windows Server 2008. As with .NET Framework 3.0, version 3.5 uses the CLR of version 2.0. In addition, it installs .NET Framework 2.0 SP1, (installs .NET Framework 2.0 SP2 with 3.5 SP1) and .NET Framework 3.0 SP1 (installs .NET Framework 3.0 SP2 with 3.5 SP1), which adds some methods and properties to the BCL classes in version 2.0 which are required for version 3.5 features such as Language Integrated Query (LINQ). These changes do not affect applications written for version 2.0, however.
As with previous versions, a new .NET Compact Framework 3.5 was released in tandem with this update in order to provide support for additional features on Windows Mobile and Windows Embedded CE devices.
The source code of the Base Class Library in this version has been partially released (for debugging reference only) under the Microsoft Reference Source License.
Changes since version 3.0
* New language features in C# 3.0 and VB.NET 9.0 compiler
* Adds support for expression trees and lambda methods
* Extension methods
* Expression trees to represent high-level source code at runtime.
* Anonymous types with static type inference
* Language Integrated Query (LINQ) along with its various providers
o LINQ to Objects
o LINQ to XML
o LINQ to SQL
* Paging support for ADO.NET
* ADO.NET synchronization API to synchronize local caches and server side datastores
* Asynchronous network I/O API.
* Peer-to-peer networking stack, including a managed PNRP resolver.
* Managed wrappers for Windows Management Instrumentation and Active Directory APIs
* Enhanced WCF and WF runtimes, which let WCF work with POX and JSON data, and also expose WF workflows as WCF services. WCF services can be made stateful using the WF persistence model.
* Support for HTTP pipelining and syndication feeds.
* ASP.NET AJAX is included
* New System.CodeDom namespace.
Service Pack 1
The .NET Framework 3.5 Service Pack 1 was released on 11 August 2008. This release adds new functionality and provides performance improvements under certain conditions, especially with WPF where 20-45% improvements are expected. Two new data service components have been added, the ADO.NET Entity Framework and ADO.NET Data Services. Two new assemblies for web development, System.Web.Abstraction and System.Web.Routing, have been added; these are used in the ASP.NET MVC Framework and, reportedly, will be utilized in the future release of ASP.NET Forms applications. Service Pack 1 is included with SQL Server 2008 and Visual Studio 2008 Service Pack 1.
There is also a new variant of the .NET Framework, called the ".NET Framework Client Profile", which at 28 MB is a lot smaller than the full framework and only installs components that are the most relevant to desktop applications. However, the Client Profile amounts to this size only if using the online installer. When using the off-line installer, the download size is still 250 MB.
Changes in 3.5 in comparison with 2.0
· .NET Framework 3.0, version 3.5 uses the CLR of version 2.0.
· Windows Workflow Foundation (WF)
· Windows Communication Foundation (WCF)
· Windows Presentation Foundation (WPF) and Windows CardSpace.
· New assemblies to avoid breaking changes.
· Deep integration of Language Integrated Query (LINQ) and data awareness.
· ASP.NET AJAX lets you create more efficient, more interactive, and highly-personalized Web experiences that work across all the most popular browsers.
· New Web protocol support for building WCF services including AJAX, JSON, REST, POX, RSS, ATOM, and several new WS-* standards.
· Full tooling support in Visual Studio 2008 for WF, WCF, and WPF, including the new workflow-enabled services technology.
· p2p base class
· Active directory
· Anonymous types with static type inference
· Paging support for ADO.NET
· ADO.NET synchronization API to synchronize local caches and server side datastores
· Support for HTTP pipelining and syndication feeds.
· New System.CodeDom namespace.

1) LINQ Support
2) Expression Blend Support
3) Windows Presentation Foundation
4) VS 2008 Multi-Targeting Support
5) AJAX support for ASP.NET
6) JavaScript Debugging Support
7) Nested Master Page Support
8) LINQ Intellisense and Javascript Intellisense support for silverlight applications
9) Intellisense Support:
10) Organize Imports or Usings
11) Intellisense Filtering
12) Intellisense Box display position
13) Visual Studio 2008 Split View
14) HTML JavaScript warnings, not as errors
15) Debugging .NET Framework Library Source Code
16)In built Silverlight Library
17) Visual Studio LINQ Designer
18) Inbuilt C++ SDK
19) Microsoft Popfly Support
.NET Framework 4.0
Microsoft announced the .NET Framework 4.0 on 29 September 2008. The Public Beta was released on 20 May 2009. Some focuses of this release are:
* Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, they plan to include technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls.
* Visual Basic and C# languages innovations such as statement lambdas, implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
* Full support for IronPython, IronRuby, and F#.
* Support for a subset of the .NET Framework and ASP.NET with the "Server Core" variant of Windows Server 2008 R2.
* Support for Code Contracts.
* Inclusion of the Oslo modelling platform, along with the M programming language.
In conjunction with .NET Framework 4.0, Microsoft will offer a set of enhancements, codenamed Dublin, for Windows Server 2008 application server capabilities. Dublin will extend IIS to be a "standard host" for applications that use either WCF or WF.
· C# Fundamentals
o C# compiler
To begin programming with C#, you first need to install a C# compiler. You can either use a command line compiler available from Microsoft or third party compiler kit such as the one developed by Mono. Microsoft's C# compiler is widely used by many developers as the Mono compiler kit is not yet fully developed. In addition to this you can also build C# applications with Visual C# .NET. It is a robust development tool used for developing all kinds of C# applications.
Microsoft's C# compiler is available in the form of a package called the .NET Software Development Kit (SDK). Visual Studio .NET comes with .NET Framework SDK.
In addition to Microsoft's C# compiler you also have an option to install Mono C# compiler kit available. Mono is a project started to create .NET compilers meant for platforms other than Windows, such as Linux. But the project is still under development and with each release of the kit more features and additional support for namespaces are added.
The upcoming version of the Mono compiler kit promises to provide support for Windows Forms, ASP.NET and ADO.NET. Moreover, the new compiler will also provide database connectivity support for MySQL databases.
C# compiler generates programs for the .NET framework, not native code.
Broadly speaking, one can compile C# classes into either executable files or dynamic link library - DLL - files. An executable file is one that can contain a runnable program (note that in the classes compiled to an executable file, there should be only one 'Main' method). A .NET dynamic link library just collects together an assembly of classes, which can then be instantiated and utilized by programs in the course of their running.
If your classes reference external classes, the C# compiler must be able to locate them. By default, the compiler only looks within the 'mscorlib.dll' assembly, which supports the basic Common Language Runtime functions. To point the compiler in the direction of other classes, use the switch described in the table below.
The following gives a list of the compiler switches we have found useful, but we would advise you to look further at the .NET documentation to see which other ones are available.
Compiler Switch
Description
/r:dll or /reference:dll
eg.
/r:System.xml.dll, System.Net.dll
This tells the C# compiler to include one or more of the .NET framework DLLs. As the standard library namespaces are not automatically referenced by the compiler, it is necessary to tell it which ones are needed. This switch also allows you to include your own DLLs.
/out: file
eg.
/out:fred.dll
Specifies the filename to which the compiled code is to be written.
/doc: file
eg.
/doc:doc.xml
Requests the production of xml documentation into the specified file (see lesson 19).
/t:type or /target:type
eg.
/t:exe - produce a console executable file (default)
/t:library - produce a dll file
/t:module - creates each file into its own dll, eg. fred.cs will be converted to fred.dll
/t:winexe - produce a windows executable file
This is used to specify the type of output file produced
If you are regularly compiling a program and using a lot of switches in your program, we have found it useful to put the compile command in a batch file rather than writing out the entire command each time.
o Data Types
Data are pieces of information that represent the qualitative or quantitative attributes of a variable or set of variables.
Almost all programming languages explicitly include the notion of data type, though different languages may use different terminology. Most programming languages also allow the programmer to define additional data types, usually by combining multiple elements of other types and defining the valid operations of the new data type. For example, a programmer might create a new data type named "Person" that specifies that data interpreted as Person would include a name and a date of birth. Common data types may include (integer, decimal, string, floating-point)
A data type also represents a constraint placed upon the interpretation of data in a type system, describing representation, interpretation and structure of values or objects stored in computer memory. The type system uses data type information to check correctness of computer programs that access or manipulate the data.
EX:
Abstract data types (store, fetch)
Algebraic data types
Composite data types
Function types
Machine data types (bit - machine code)
Object types
Pointer and reference data types
Primitive data types
C# is a "Strongly Typed" language. Thus all operations on variables are performed with consideration of what the variable's "Type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable.
Data is physically stored inside cells of memory. This memory could be physical memory (Hard disk) or logical memory (RAM). Any cell of memory is represented with a unique address. This address is more than some combination of numbers or symbols.
C# language provides for practically all the data types. These types can be divided in three categories: value types, reference types and pointer types.
There are some more basic concepts to be learnt before the discussion of the data types. This is about variables and constants. A Variable is a named cell of memory used for data storage. A Variable value can be changed anytime. Every variable must have a type and this type must be set before it is used. Qualifying a variable with a type is called as declaration of variable. The type of a variable is the most important aspect and it defines the behavior of variable. All variables can be divided into seven main categories depending on the context of usage:
1. Static variables
2. Variable of instance
3. Array's elements
4. Parameters given by reference
5. Parameters given by value
6. Returned values
7. Local variables.
http://www.codersource.net/csharp_tutorial_data_types.html
§ Value Types
In object-oriented programming, a value type is a data type that can exist outside dynamic memory allocation. Unlike reference types, value types can be directly embedded into composite objects.
Primitive types are always value types.
Value types can exist in dynamically allocated memory, such as embedded into a dynamic object. Some platforms also allow direct dynamic allocation of value objects, while others require the value to be copied into a specific dynamic object. The later process is called boxing.
On some platforms, a value may be directly linked to by a pointer or reference. On others, it is a prerogative of reference types.
Value types represent primitive values such as integers or floating-point values. There are three general categories of value types: enumerations, which are described in detail in Chapter 10; built-in value types; and user-defined value types, or structs. As we have seen, value types store their data directly on the stack. Since parameters are by default passed by value in C#, when a value-type parameter is passed into a method, a new copy of the value is created; any changes made to the parameter won't result in changes to the variable passed into the method. Method parameters are discussed in detail in Chapter 12.
Main Features of Value Types
A variable of a value type always contains a value of that type. The assignment to a variable of a value type creates a copy of the assigned value, while the assignment to a variable of a reference type creates a copy of the reference but not of the referenced object.
All value types are derived implicitly from the Object class.
Unlike reference types, it is not possible to derive a new type from a value type. However, like reference types, structs can implement interfaces.
Unlike reference types, it is not possible for a value type to contain the null value.
Each value type has an implicit default constructor that initializes the default value of that type. For information on default values of value types, see Default Values Table.
Initializing Value Types
Local variables in C# must be initialized before being used. Therefore, if you declare a local variable without initialization like this:
int myInt;
you cannot use it before you initialize it. You can initialize it using the following statement:
myInt = new int(); // Using the new operator calls the default constructor of the specific type and assigns the default value to the variable.
 
myInt = 0;
 
 
· Predefined Value Types
The .NET Framework provides a number of predefined value types. These represent various integer, floating point, character, and Boolean values. In other programming languages these are often referred to as primitive data types. The built-in data types of the .NET Framework are defined as structures and can be found in the System namespace. A list of the built-in value types available in C# is given below:
EX: Boolean, Byte, Char, Decimal, Double, Int 16/32/64,
C# provides a set of predefined types, most of which will be familiar to C and C++ developers.
The predefined reference types are object and string. The type object is the ultimate base type of all other types. The type string is used to represent Unicode string values. Values of type string are immutable.
The predefined value types include signed and unsigned integral types, floating-point types, and the types bool, char, and decimal. The signed integral types are sbyte, short, int, and long; the unsigned integral types are byte, ushort, uint, and ulong; and the floating-point types are float and double.
The bool type is used to represent Boolean values: values that are either true or false. The inclusion of bool makes it easier to write self-documenting code; it also helps eliminate the all-too-common C++ coding error in which a developer mistakenly uses "=" when "==" should have been used.
· Nullable Types
So .Net Framework 2.0 comes out with a great new feature and solution to your problem. It is The Nullable Value Types. I'm saying .Net Framework to generalize the feature as it is a new feature in both C# and VB.NET.
In .Net Framework 2.0, value types can be extended to take either their normal values or a null value. Such an extension is called a nullable type. Nullable type is constructed from the generic Nullable structure. By having this feature, you can submit null values to you database table field normally, like submitting a null DateTime value to a datetime field in your database table.
Nullable types are instances of the System.Nullable struct.
Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
An instance of the Nullable type has two public properties.
* HasValue - A Boolean property denoting the validity of the value contained in the object.
* Value - A value contained in the object.
The 'true' value for the HasValue property guarantees the validity of the value contained in the object which can be accessed through the Value property. A 'false' value for the HasValue indicates the invalid value contained by the object suggesting not to use the Value property.
An instance for which HasValue is false is said to be null. A null instance has an undefined value. Attempting to read the Value of a null instance causes a System.InvalidOperationException to be thrown.
Taking about the default values for the Nullable type we can say; Any instance of a Nullable type is said to have a default value when the HasValue is set to 'false' and the value property is undefined. This value is known as an null value of an Nullable type. While implicitly converting the 'null' value to any nullable type values the conversion results in the null value of the nullable type.
Simply like this:
C#
DataTime? dtmVarName = null;
int? intVarName = null;
bool? bVarName = null;
VB.NET
Dim dtmVarName As Nullable(Of DateTime)
Dim intVarName As Nullable(Of Integer)
Dim bVarName As Nullable(Of Boolean
§ Reference Types
In programming language theory, a reference type is a data type that can only be accessed by references. Unlike objects of value types, objects of reference types cannot be directly embedded into composite objects and are always dynamically allocated. They are usually destroyed automatically after they become unreachable.
For immutable objects, the distinction between reference type to an immutable object type and value type is sometimes unclear, because a reference type variable to an immutable object behaves with the same semantics as a value type variable—for example, in both cases the "value" of the data the variable represents can only be changed by direct assignment to the variable (whereas for mutable objects, the data could be changed by modifying the object through another reference to the object).
Reference types store a reference to the value’s memory address and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The data type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.
The .NET Framework includes a variety of reference types; this includes the String object, along with all arrays (even if their elements are value types), class types, and delegates. You can think of a reference type as anything that inherits from the Object class; this means that every object you create is a reference type.
One way to identify a reference type is by using a new keyword that isn’t used for value types. The following C# snippet shows the creation of a StringBuilder object, which is a reference type.
StringBuilder sb = new StringBuilder();
When the runtime deals with reference types, it allocates two spaces in memory: one for the actual object (StringBuilder in the previous example) and one for its reference (sb in the previous example). The actual object is stored on the managed heap, so it is within the reach of the garbage collector. The dispose method is used to release its memory and make it available to the garbage collector.
On the other hand, the reference to the object is stored on the stack. When using reference types, the ref keyword is used in both the method signature and when it is called in C# to tell the system that you are working with a reference to the object. In VB.NET, ByRef is used in the method signature with nothing when the method is called.
§ User-defined Types
A user-defined type (UDT) is a named data type that is created in the database by the user. A UDT can be a distinct type which shares a common representation with a built-in data type or a structured type which has a sequence of named attributes that each has a type.
There are three types of user-defined data type:
* Distinct type
* Structured type
* Reference type
Distinct types
A distinct type is a user-defined data type that shares its internal representation with an existing type (its "source" type), but is considered to be a separate and incompatible type for most operations. For example, one might want to define a picture type, a text type, and an audio type, all of which have quite different semantics, but which use the built-in data type BLOB for their internal representation.
Structured types
A structured type is a user-defined data type that has a structure that is defined in the database. It contains a sequence of named attributes, each of which has a data type. A structured type also includes a set of method specifications.
Reference types
A reference type is a companion type to a structured type. Similar to a distinct type, a reference type is a scalar type that shares a common representation with one of the built-in data types. This same representation is shared for all types in the type hierarchy. The reference type representation is defined when the root type of a type hierarchy is created. When using a reference type, a structured type is specified as a parameter of the type. This parameter is called the target type of the reference.
§ Anonymous Types
Anonymous types are new in C# 3.0 and VB 9.0 (Visual Studio 2008). An anonymous type allows you to encapsulate a set of properties (not methods) into a specific object without explicitly defining a type. Anonymous types are a convenient language feature of C# and VB that enable developers to concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.
Anonymous types are particularly useful when querying and transforming/projecting/shaping data with LINQ.
When you create a class, such as a Customer class, you are explicitly creating a Customer type with defined properties and methods. The resulting class defines a Customer type which is a named type with the name Customer.
There are times, however, where you need a temporary type. You could explicitly create this type using a class, but that seems like overkill if you only plan to use the type within one routine. This is where an anonymous type is very useful.
It is important to note that the properties of an anonymous type are read/write in VB, but read-only in C#.
var stats = new {Name = String.Empty, Max = 0,
Min = 0, Ave = 0};
§ Type Conversion
Conversion is the process of changing a value from one type to another. Conversions may either be widening or narrowing.
Widening conversions: When a particular data type is converted to a data type that is capable of storing more data than the source data type is referred to as widening conversion. The simple examples of widening conversion can be Numeric type conversions in the direction Byte, Short, Integer, Long, Decimal, Single, Double, here every type listed to the right of a type is capable of storing more data than its left listed type. If we takes the case of reference data types then Conversions from any derived type to one of its base types is also referred to as widening conversion. Widening conversion never cause overflow.
Narrowing conversions: A narrowing conversion occurs when a variable is converted to a type that is not capable of storing the data held by the source data type variable. These conversions are known to possibly lose information and conversions across domains of types sufficiently different to merit narrowing notation. These means narrowing conversions entail loss of information and may fail.
Reference conversions: These are conversion from one reference type to another. Reference conversions, implicit or explicit, never change the referential identity of the object being converted. In other words, while a reference conversion may change the type of the reference, it never changes the type or value of the object being referred to.
Boxing and Un-boxing conversions: A boxing conversion permits any value-type to be converted to the type object or to any interface-type implemented by the value-type. Boxing a value of a value-type consists of allocating an object instance and copying the value-type value into that instance. 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:
Interface conversion: Converting an interface to a value type consists of copying the value in the interface instance to the target variable (which may be a temporary).
Conversion operators:
C# allows the pre-defined implicit and explicit conversions to be augmented by user-defined conversions. User-defined conversions are introduced by declaring conversion operators in class and struct types.
Implicit conversion: The implicit keyword is used to declare an implicit user-defined type conversion operator.
SomeType x;
int i = x; // implicitly call SomeType's implicit conversion function that returns int value.
Explicit Conversions: Explicit conversion is performed using casting. Casting occurs when you prefix a conversion with a data type that defines the type of the conversion you want to perform. The explicit keyword is used to declare an explicit user-defined type conversion operator. The set of explicit conversions includes all implicit conversions. Example:
int i;
SomeType x = (SomeType)i;
o Flow Control
That is, execution began at the first line of code and progressed through line-by-line until the end of the example was reached. In the real world, this type of program is very rare for anything except the most basic tasks. For complex software program flow control statements are a necessity.
Program flow control statements can be divided into four categories
* Loops. Loops allow a defined section of code to be executed multiple times until a condition is met. A loop structure is the main focus of this article.
* Conditional Processing. Conditional processing statements and structures permit code to be executed only when certain defined conditions are met. These statements will be the topic for a later article in the tutorial.
* Jumps. Jump statements are simple commands that can be used to immediately transfer the control of a program to another statement. The break and continue jump statements are described in this article. The infamous goto statement will be considered later.
* Exception Handling. When exceptions occur, rather than simply presenting the user with an error and stopping execution of the program, they should be handled. Exception handling statements provide this capability and will be described in a later article in this tutorial.
o Looping
Ability to repeat a block of code X times. C# provides a number of the common loop statements:
· while
· do-while
· for
· foreach
o Operators
Operators are symbols and notations used in a programming language to express a certain statement. For example if we want to add two variables, we would use the "+" operator.
C# has a large number of operators, some will be used in every single program or module, while others you may not ever use.
The most common of the operators are the arithmetic and logic operators.
Category (by precedence)
Operator(s)
Associativity
Primary
x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate
left
Unary
+ - ! ~ ++x --x (T)x
left
Multiplicative
* / %
left
Additive
+ -
left
Shift
<< >>
left
Relational
< > <= >= is as
left
Equality
== !=
right
Logical AND
&
left
Logical XOR
^
left
Logical OR
|
left
Conditional AND
&&
left
Conditional OR
||
left
Null Coalescing
??
left
Ternary
?:
right
Assignment
= *= /= %= += -= <<= >>= &= ^= |= =>
right
o Preprocessor Directives
C# preprocessor is fundamentally very similar to C preprocessor and the whole concept in C# has been taken from C language specification.
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.
But in C# only concept has been taken from C. But the C# compiler does not have a separate preprocessor, the directives described in this C# are processed as if there was one. Unlike C and C++ directives, you cannot use these directives to create macros.
A preprocessor directive must be the only instruction on a line. Preprocessing directives are lines in your program that start with `#'. Whitespace is allowed before and after the `#'. The `#' is followed by an identifier that is the directive name. For example, `#define' is the directive The C# language's preprocessor directives are as follows:
#if
#else
#elif
#endif
#define
#undef
#warning
#error
#line
#region
#endregion
Main use of directives are:
1.Conditional compilation. Using special preprocessing directives, you can include or exclude parts of the program according to various conditions.
2.Line control. If you use a program to combine or rearrange source files into an intermediate file, which is then compiled, you can use line control to inform the compiler of where each source line originally came from.
3.Error and Warning reporting. The directive `#error' causes the preprocessor to report a fatal error and the directive `#warning' is like the directive `#error', but causes the preprocessor to issue a warning and continue preprocessing.
· Classes and Objects
C# .NET is an Object Oriented programming language. Objects are created from Classes, which you've already used a lot. The Windows Form itself is a Class, and when you run your programme, you are creating Objects: a Form object, a button object, a Textbox object, etc. In this section, you'll learn how to write your own Classes, and turn them in to Objects
o Classes
A Class is simply a chuck of code that does a particular job. The idea is that you can reuse this code (Class) whenever you need it, or when you need it in other projects. It saves you from having to write the same thing over and over again.
o Objects
You do all the coding in a Class (recipe), and then instruct C# to make an object (a Banana Cake). The two processes are different.
But all you are really doing with Classes and Objects is trying to separate code into chunks, so that it can be reused. When the code is being used, it's an object. But the object is created from your code (Class).
§ Defining a Class
A Class is simply a chuck of code that does a particular job. The idea is that you can reuse this code (Class) whenever you need it, or when you need it in other projects. It saves you from having to write the same thing over and over again.
§ Using Partial Classes
Partial classes mean that your class definition can be split into multiple physical files.
Logically, partial classes do not make any difference to the compiler. During compile time, it simply groups all the various partial classes and treats them as a single entity.
One of the greatest benefits of partial classes is that it allows a clean separation of business logic and the user interface (in particular the code that is generated by the visual designer). Using partial classes, the UI code can be hidden from the developer, who usually has no need to access it anyway. Partial classes will also make debugging easier, as the code is partitioned into separate files.
§ Anonymous Types (C# 3.0)
The C# 3.0 specifications describe anonymous types as tuple types automatically inferred and created from object initializers. Before you can fully understand the meaning of this definition, you need to understand the term "object initializer," which is the basis of the anonymous types feature. That allows data types to encapsulate a set of properties into a single object without having to first explicitly define a type.
This is an important feature for the SQL-like Language Integrated Query (LINQ) feature that is integrated into C# and VB.net. Since anonymous types do not have a named typing, they must be stored in variables declared using the var keyword, telling the C# compiler to use type inference for the variable. The properties created are read-only in C#, however they are read-write in VB.net.
var Customer = new
{
    Company = "West Wind",
    Name = "Rick",
    Entered = DateTime.Now,
    BillRate = 150M,
    Contacts = new
    {
        Phone = "808 121-1211",
        Fax = "808 231-1211",
        Email = "rick@west-wind.com"
    }
};
List listOfCustomers =
        new List {
            { Id = 1, Name="Dave", City="Sarasota" },
            { Id = 2, Name="John", City="Tampa" },
            { Id = 3, Name="Abe", City="Miami" }
        };
This code creates a new instance of an anonymous type - in this case a simple object instance that holds customer data. Once you have declared the type like the above you can then use the type as if there was a full type declaration, so you can access Customer.Company, Customer.BillRate and so forth.
Visual Studio 2008 is also smart enough to figure out the anonymous type for you so when you're in the editor typing away you get Intellisense when you type Customer.:
§ Instance Members
Instance members belong to the object that they are instantiated from. While this may sound somewhat cryptic, it will all become much clearer with the following code:
public class GenerateClones
{
    public void main()
    {
        //Instantiate our class and create a clone
        CloneGenerator c1 = new CloneGenerator("Bob");
        CloneGenerator c2 = new CloneGenerator("Jon");
        CloneGenerator c3 = new CloneGenerator("Jim");
 
        //this string will contain the name Bob
        string clone1 = c1.getName();
        
        //this string will contain the name Jon
        string clone2 = c2.getName();
 
        //this string will contain the name Jim
        string clone3 = c3.getName();
 
        //Call the Static function
        //iCloneCount will hold the value of 3 after this assignment
        int iCloneCount = CloneGenerator.countClones();        
    }
}
Static members are not associated with a specific instance of a class. To call a static member, you qualify the static member with the class name. Because static members are not associated with object instances, they do not have access to non-static members
For example, MyClass.StatMember
Because static members are not associated with object instances, they do not have access to non-static members.
Non-static members are called instance members because they are associated with individual object instances. Think of static members as belonging to the class and instance members belonging to instances of the class (that is, objects).
§ Static Members
Static members are not associated with a specific instance of a class. To call a static member, you qualify the static member with the class name. Because static members are not associated with object instances, they do not have access to non-static members
For example, MyClass.StatMember
Because static members are not associated with object instances, they do not have access to non-static members.
§ Access modifiers
Access Modifiers (Access Specifiers) describes as the scope of accessibility of an Object and its members. All C# types and type members have an accessibility level. We can control the scope of the member object of a class using access specifiers. We are using access modifiers for providing security of our applications. When we specify the accessibility of a type or member we have to declare it by using any of the access modifiers provided by CSharp language.
public: public is the most common access specifier in C# . It can be access from anywhere that means there is no restriction on accessibility. The scope of the accessibility is inside class as well as outside. The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private : The scope of the accessibility is limited only inside the classes or struct in which they are declared. The private members cannot be accessed outside the class and it is the least permissive access level.
protected : The scope of accessibility is limited within the class or struct and the class derived (Inherited )from this class.
Internal : The internal access modifiers can access within the program that contain its declarations and also access within the same assembly level but not from another assembly.
protected internal : Protected internal is the same access levels of both protected and internal. It can access anywhere in the same assembly and in the same class also the classes inherited from the same class.

§ Function Members
Function members are members that contain executable statements. Function members are always members of types and cannot be members of namespaces. C# defines the following categories of function members:
* Methods
* Properties
* Events
* Indexers
* User-defined operators
* Instance constructors
* Static constructors
* Finalizers
· Methods
Method is object-oriented item of any language. All C# programs are constructed from a number of classes and almost all the classes will contain methods. A class when instantiated is called an object. Object-oriented concepts of programming say that the data members of each object represent its state and methods represent the object behavior.
EX: Return-type methodname ( Parameterslist );
The input parameters can be passed in two ways.
* Value type
public int CalculateBirthYear(int year)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
* Reference type.
public int CalculateBirthYear(ref int year)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
o this keyword
The "this" keyword gets you an access to an instance of the class, and you can use it with instance methods, instance constructors and instance properties. You can't use it with any static members; this makes sense because a static member works on the class itself, not on an instance of it. Use the "this" keyword followed by the (.) operator to get access to the class members on an instance object. Take a look at the following class:
using System;
namespace Company
{
public class Employee
{
public string FirstName;
public string LastName;

//the default constructor
public Employee()
{
this.FirstName = "Michael";
this.LastName = "Youssef";
}
}
}
· Properties (Read only and write only properties)
  • Properties are used to get or set the value of data members of a class.
  • They are used to implement data security.
  • A property contains two blocks: (i) get and (ii) set. These blocks works on the basis of calling conventions.
  • get and set block is implicit calling of grammar language. Property is define public normally to have get and set control.
  • For each data members we have to create one property.
  • In c-sharp we create indexers in place of parameterized property. (In VB you can have parameterized property).
  • For static data member static properties are used.

Difference between Property and Methods

Property

  1. Property is implicitly called using calling convention
  2. Property works on compile and runtime.
Method
  1. Method is explicitly called
  2. Methods works on runtime.
If you define a property with only a get accessor, that property will be read-only. Likewise, if you define a property with only a set accessor, you’ll end up with a write-only property. And lastly, a property with both accessors is a read-write property.
· Partial Methods
C# 3.0, we can now have partial method. Partial methods are the code block which reside inside a partial type and gets executed only when it has definition. This gives us the extensibility and if user wants to implement the rule, they can go ahead and define the body but if they do not want it will not. This improves the performance as you are not loading/creating unwanted methods.
public partial class MyClass
{
//Public Constructor
public MyClass(int iInput)
{
//Calling Partial Method
GetMessage(iInput);
}
//Public Property
public string Messgae { get; set; }
//Partial Method
partial void GetMessage(int iVal);
}
In the partial method declaration I cannot have any body. So, where we need to define the body of our method?
Should be in another partial. But since there is no body, the method actually will have no existence in IL.
Ø A partial method must be declared within a partial class or partial struct
Ø A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers
Ø Partial methods must have a void return type
Ø A partial method cannot have out parameters
Ø Definition has to end with “;” No {} is allowed in this scope.
# Can be marked static or unsafe.
# Can be generic.
# Can have ref but not out parameters.
# Cannot be referenced as a delegate until they are implemented
# Cannot have access modifiers such as public, private or internal.
# Cannot be declared as virtual.
§ Constructors
Constructor is a special kind of method of a class, which gets executed when its (class) object is created.
What is constructor?
  • Constructor is used to initialize an object (instance) of a class.
  • Constructor is a like a method without any return type.
  • Constructor has same name as class name.
  • Constructor follows the access scope (Can be private, protected, public, Internal and external).
  • Constructor can be overloaded.
Constructors generally following types :
  • Default Constructor
  • Parameterized constructor
  • Private Constructor
  • Static Constructor
  • Copy Constructor
Default Constructor
A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.
Parameterized constructor
Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.
Private Constructor
Private Constructors are used to restrict the instantiation of object using 'new' operator. A private constructor is a special instance constructor. It is commonly used in classes that contain static members only.
This type of constructors is mainly used for creating singleton object.
If you don't want the class to be inherited we declare its constructor private.
We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private.
Static Constructors
C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor).
Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster.
Static constructors are used to initializing class static data members.
Point to be remembered while creating static constructor:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.

Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members.
Copy Constructor
If you create a new object and want to copy the values from an existing object, you use copy constructor.
This constructor takes a single argument: a reference to the object to be copied.
· Constructor Chaining
Constructor chaining occurs through the use of inheritance. A subclass constructor method's first task is to call its superclass' constructor method. This ensures that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain.
There could be any number of classes in an inheritance chain. Every constructor method will call up the chain until the class at the top has been reached and initialized. Then each subsequent class below is initialized as the chain winds back down to the original subclass. This process is called constructor chaining.
Another approach is to use constructor chaining, where a constructor calls another constructor in its class using the ": this()" designation as shown below:
public Test( bool a, int b, string c ): this( a, b )
{
    this.m_C = c;
}
public Test( bool a, int b, float d ): this( a, b )
{
    this.m_D = d;
}
private Test( bool a, int b )
{
    this.m_A = a;
    this.m_B = b;
}
§ Destructors
The .NET framework has an in built mechanism called Garbage Collection to de-allocate memory occupied by the un-used objects. The destructor implements the statements to be executed during the garbage collection process. A destructor is a function with the same name as the name of the class but starting with the character ~.
Remember that a destructor can't have any modifiers like private, public etc. If we declare a destructor with a modifier, the compiler will show an error.Also destructor will come in only one form, without any arguments. There is no parameterized destructor in C#.
Destructors are invoked automatically and can't be invoked explicitly. An object becomes eligible for garbage collection, when it is no longer used by the active part of the program. Execution of destructor may occur at any time after the instance or object becomes eligible for destruction.
Example:
class Complex
{
public Complex()
{
// constructor }
~Complex()
{
// Destructor }
}
§ Static Classes
We use static class when there is no data or behavior in the class that depends on object identity. A static class can have only static members. We cannot create instances of a static class using the new keyword. .NET Framework common language runtime (CLR) loads Static classes automatically when the program or namespace containing the class is loaded.
Features
Static classes only contain static members.
Static classes cannot be instantiated. They cannot contain Instance Constructors
Static classes are sealed.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.
static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
}
public static class SystemSettings
{
static int _maximumFiles;
public static int MaximumFiles
{
get { return _maximumFiles; }
set { _maximumFiles = value; }
}
static SystemSettings()
{
_maximumFiles = 20;
}
}
o System.Object Class
The Object class, held in the System namespace, is the base class for all classes and data types, including the value types. It is the class at the root of the .NET framework class library's entire type hierarchy.
System.Object defines several public and protected methods that, due to inheritance, are automatically made available to all .NET classes, structures and types, including any classes or structures that you create yourself. If you create a class with no base class specified, it will implicitly derive functionality from Object.
§ Testing For Equality
§ Implementing Equals
§ ToString() Method
ToString returns a human-readable string that is culture-sensitive. For example, for an instance of the Double class whose value is zero, the implementation of Double.ToString might return "0.00" or "0,00" depending on the current UI culture. Here I compare ToString() with no parameters (no format string) and ToString() with the NumberFormatInfo specified. ToString() can receive a System.Globalization. NumberFormatInfo parameter.
§ Attributes
Attributes are elements that allow you to add declarative information to your programs. This declarative information is used for various purposes during runtime and can be used at design time by application development tools. For example, there are attributes such as DllImportAttribute that allow a program to communicate with the Win32 libraries. Another attribute, ObsoleteAttribute, causes a compile-time warning to appear, letting the developer know that a method should no longer be used. When building Windows forms applications, there are several attributes that allow visual components to be drag-n-dropped onto a visual form builder and have their information appear in the properties grid. Attributes are also used extensively in securing .NET assemblies, forcing calling code to be evaluated against pre-defined security constraints. These are just a few descriptions of how attributes are used in C# programs.
· Custom Attributes
.net allows the use of custom attributes. Custom Attributes can be used to store information that can be stored at compile time and retrieved at run time. This information can be related to any aspect/feature of target element depending upon the design of application. We will develop a custom attribute ClassInfoAttribute, which will be used for storing information, related to source code. CodeInfoAttribute will have the following information.
  • DeveloperName
  • ReviewerName
  • ReviewDate
public class DescriptionAttribute: Attribute {
        private string description;
 
        public string Description {get {return description;}}
 
        public DescriptionAttribute(string description) {
               this.description = description;
        }
}
o Structures
Structures (keyword struct) are light-weight objects. They are mostly used when only a data container is required for a collection of value type variables. Structs are similar to classes in that they can have constructors, methods, and even implement interfaces, but there are important differences.
* Structs are value types while classes are reference types, which means they behave differently when passed into methods as parameters.
* Structs cannot support inheritance. While structs may appear to be limited with their use, they require less memory and can be less expensive if used in the proper way.
* Structs always have a default constructor, even if you don't want one. Classes allow you to hide the constructor away by using the "private" modifier, whereas structures must have one.
using System;
struct Person
{
    string name;
    DateTime birthDate;
    int heightInCm;
    int weightInKg;
 
    public Person(string name, DateTime birthDate, int heightInCm, int weightInKg)
    {
        this.name = name;
        this.birthDate = birthDate;
        this.heightInCm = heightInCm;
        this.weightInKg = weightInKg;
    }
}
 
public class StructWikiBookSample
{
    public static void Main()
    {
        Person dana = new Person("Dana Developer", new DateTime(1974, 7, 18), 178, 50);
    }
}
 
· Interfaces
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.
Why use Interface?
1. To allow a class to inherit multiple behaviors from multiple interfaces.
2. To avoid name ambiguity between the methods of the different classes as was in the use of multiple inheritances in C++.
3. To combine two or more interfaces such that a class need only implement the combined result. The example code for this is provided as a source file to be downloaded.
4. To allow Name hiding. Name hiding is the ability to hide an inherited member name from any code outside the derived class.
o Defining an Interface
Interface INode
{
String Text{get;set;}
Object Tag{get;set;}
}
o Implementing an Interface
using System;
namespace PavelTsekov
{
   interface I1
   {
      void MyFunction();
   }
   interface I2
   {
      void MyFunction();
   }
   class Test : I1,I2
   {
      void I1.MyFunction()
      {
        Console.WriteLine("Now I can say this here is I1 implemented!");
      }
      void I2.MyFunction()
      {
        Console.WriteLine("Now I can say this here is I2 implemented!");
      }
   }
   class AppClass
   {
      public static void Main(string[] args)
      {
        Test t=new Test();
        I1 i1=(I1)t;
        i1.MyFunction();
        I2 i2=(I2)t;
        i2.MyFunction();
      }
   }
}
o Implementing Multiple Interfaces
1:  //  Multi.cs -
 2:  //-----------------------------------------------------------
 3:
 4:  using System;
 5:
 6:  public interface IShape
 7: {
 8:     // Cut out other methods to simplify example.
 9:     double Area();
10:     int Sides { get; }
11:  }
12:
13:  public interface IShapeDisplay
14:  {
15:     void Display();
16:  }
17:
18:  public class Square : IShape, IShapeDisplay
19:  {
20:     private int InSides;
21:     public  int SideLength;
22:
23:     public int Sides
24:     {
25:        get { return InSides; }
26:     }
27:
28:     public double Area()
29:     {
30:        return ((double) (SideLength * SideLength));
31:     }
32:
33:     public double Circumference()
34:     {
35:        return ((double) (Sides * SideLength));
36:     }
37:
38:     public Square()
39:     {
40:        InSides = 4;
41:     }
42:
43:     public void Display()
44:     {
45:        Console.WriteLine("\nDisplaying Square information:");
46:        Console.WriteLine("Side length: {0}", this.SideLength);
47:        Console.WriteLine("Sides: {0}", this.Sides);
48:        Console.WriteLine("Area: {0}", this.Area());
49:     }
50:  }
51:
52:  public class Multi
53:  {
54:     public static void Main()
55:     {
56:        Square mySquare = new Square();
57:        mySquare.SideLength = 7;
58:
59:        mySquare.Display();
60:     }
61:  }

Output

Displaying Square information:
Side length: 7
Sides: 4
Area: 49
o Extending Interfaces
  • Interfaces can be extended using the extends keyword.
  • Interfaces can extend more than one interface:
· interface Shimmer extends FloorWax, DessertTopping \{ \ldots
  • All methods and constants defined by FloorWax and DessertTopping are part of Shimmer.
o Interface Casting
Using the as operator is a better coding strategy than a straight cast because it yields a null on a conversion failure rather than raising an exception.
The first line of code below is a straight cast. This is acceptable practice if you are absolutely certain the object in question implements both interfaces; if the object does not implement the interface you are attempting to get a handle to, .NET will throw an exception. A safer model to use is the as operator, which returns a null if the object cannot return a reference to the desired interface.
IGeometry geometry = point;               // straight cast
IGeometry geometry = point as IGeometry;  // as operator 
o The is and as operators
The is Operator
You can handle incompatible types by catching InvalidCastException, but there are other ways of handling this problem, such as the is operator. The is operator allows you to determine whether an object reference can be converted into a reference to a given class.
You can use the is operator to test the type of the object without performing a conversion. The is operator returns true if the value on the left is not null and a cast to the class on the right, if performed, would complete without throwing an exception. Otherwise, is returns false.
if (a is Bird)
b = (Bird) a; // Safe, because "a is Bird" returns true
else
Console.WriteLine("Not a Bird");
The as Operator
You can use the as operator to perform conversions between types without raising an exception.
The following statement performs a conversion of the reference in a to a value that references a class of type Bird, and the runtime automatically checks to ensure that the conversion is acceptable.
b = a as Bird;
The as operator differs from the cast operator in the way it handles errors. If, in the preceding example, the reference in variable a cannot be converted in a reference to an object of class Bird, the value null is stored in b, and the program continues. The as operator never raises an exception.
You can rewrite the previous code as follows to display an error message if the conversion cannot be performed:
Bird b = a as Bird;
if (b == null)
Console.WriteLine("Not a bird");
o Overriding Interface Implementations
· Inheritance
It allows a class to be defined which has a number of characteristics and then other classes to be created which are derived from that class. The derived class inherits all of the features of the parent class and typically then adds some features of its own.
By deriving classes we create what is often referred to as a class hierarchy. The class at the top of the hierarchy is known as the base class and the derived classes as subclasses. Any number of classes may be derived from a class. It is only possible for a derived class to inherit from one class. As such, C# is known as a single inheritance programming language.
C# supports two types of Inheritance mechanisms
1) Implementation Inheritance
2) Interface Inheritance
o Understanding Inheritance in C#
o Implementation inheritance
When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance
o Interface inheritance
When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance
In general Classes can be derived from another class, hence support Implementation inheritance At the same time Classes can also be derived from one or more interfaces Hence they support Interface inheritance Structs can derive from one more interface, hence support Interface Inheritance Structs cannot be derived from another class they are always derived from SystemValueType
o Explicit Interface Member Implementation
C# does not support multiple inheritances, but a class has the option of implementing one or more interfaces. One challenge with interfaces is that they may include methods that have the same signatures as existing class members or members of other interfaces. Explicit interface implementations can be used to disambiguate class and interface methods that would otherwise conflict. Explicit interfaces can also be used to hide the details of an interface that the class developer considers private.
· Inheritance
Inheritance is specific to object-oriented programming, where a new class is created from an existing class. Inheritance (often referred to as subclasses) comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class. The main advantage of inheritance is the ability to define new attributes and new methods for the subclass which are then applied to the inherited attributes and methods.
This can be used to create a highly specialized hierarchical class structure. The biggest advantage is that there is no need to start from scratch when wanting to specialize an existing class. As a result, class libraries can be purchased; providing a base that can then be specialized at will (the company selling these classes tends to protect member data using encapsulation).
1) single inheritance
public class A
{
}
public class B:A
{
}
2)multiple inheritance
public class A
{
}
public class B
{
}
public class C:A,B
{
}
3)multilevel inheritance
public class A
{
}
public class B:A
{
}
public class C:B
{
}
4)hierarchial inheritance
o Understanding Inheritance in C#
C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance.
o Implementation inheritance
ChildClass has exactly the same capabilities as ParentClass. Because of this, you can also say ChildClass "is" a ParentClass. This is shown in the Main() method of ChildClass when the print() method is called. ChildClass does not have its own print() method, so it uses the ParentClass print() method. You can see the results in the 3rd line of output.
Base classes are automatically instantiated before derived classes. The ParentClass constructor executed before the ChildClass constructor.
using System;
public class Parent
{
string parentString;
public Parent()
{
Console.WriteLine("Parent Constructor.");
}
public Parent(string myString)
{
parentString = myString;
Console.WriteLine(parentString);
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class Child : Parent
{
public Child() : base("From Derived")
{
Console.WriteLine("Child Constructor.");
}
public new void print()
{
base.print();
Console.WriteLine("I'm a Child Class.");
}
public static void Main()
{
Child child = new Child();
child.print();
((Parent)child).print();
}
}
Output:
     From Derived

    Child Constructor.

    I'm a Parent Class.

    I'm a Child Class.

    I'm a Parent Class.
o Interface inheritance
Interface inheritance is the process of defining a new interface with all the methods found in one or more old interfaces. Unlike Object Oriented Inheritance, where all the methods (there implementations) and attributes of a base class are found in the derived class, interface inheritance only specifies that the names of the methods and attributes in the base interface is found in the derived interface. Like inheritance diagrams which describe model inheritance, lattice graphs are used to model interface inheritance.
        // Example #1 : IDL Base Class
        interface IBase
        {
        void BaseMethod();
        };
 
        // Derived Class
        interface IDerived : IBase
        {
        void DerivedMethod( );
        };
o Explicit Interface Member Implementation
· Delegates and Events

Delegates

A delegate is a C# language element that allows you to reference a method. If you were a C or C++ programmer, this would sound familiar because a delegate is basically a function pointer. However, developers who have used other languages are probably wondering, "Why do I need a reference to a method?”
using System;
// this is the delegate declaration
public delegate int Comparer(object obj1, object obj2);
public class Name
{
public string FirstName = null;
public string LastName = null;
public Name(string first, string last)
{
FirstName = first;
LastName = last;
}
// this is the delegate method handler
public static int CompareFirstNames(object name1, object name2)
{
string n1 = ((Name)name1).FirstName;
string n2 = ((Name)name2).FirstName;
if (String.Compare(n1, n2) > 0)
{
return 1;
}
else if (String.Compare(n1, n2) <>
{
return -1;
}
else
{
return 0;
}
}
public override string ToString()
{
return FirstName + " " + LastName;
}
}

Events

A C# event is a class member that is activated whenever the event it was designed for occurs. I like to use the term "fires" when the event is activated. Anyone interested in the event can register and be notified as soon as the event fires. At the time an event fires, registered methods will be invoked.
Events and delegates work hand-in-hand to provide a program's functionality. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.
using System;
using System.Drawing;
using System.Windows.Forms;

// custom delegate public delegate void Startdelegate();

class Eventdemo : Form
{ // custom event public event Startdelegate StartEvent;

public Eventdemo()
{
Button clickMe = new Button();

clickMe.Parent = this;
clickMe.Text = "Click Me";
clickMe.Location = new Point(
(ClientSize.Width - clickMe.Width) /2,
(ClientSize.Height - clickMe.Height)/2);

// an EventHandler delegate is assigned
// to the button's Click event
clickMe.Click += new EventHandler(OnClickMeClicked);

// our custom "Startdelegate" delegate is assigned
// to our custom "StartEvent" event.
StartEvent += new Startdelegate(OnStartEvent);

// fire our custom event StartEvent();
}

// this method is called when the "clickMe" button is pressed
public void OnClickMeClicked(object sender, EventArgs ea)
{
MessageBox.Show("You Clicked My Button!");
}
// this method is called when the "StartEvent" Event is fired public void OnStartEvent()
{
MessageBox.Show("I Just Started!");
}

static
void Main(string[] args)
{
Application.Run(new Eventdemo());
}
}

· Strings and Regular Expressions
A string is generally understood as a data type storing a sequence of data values, usually bytes, in which elements usually stand for characters according to a character encoding, which differentiates it from the more general array data type. In this context, the terms binary string and byte string are used to suggest strings in which the stored data does not (necessarily) represent text.
Regular Expressions is a formatted string. Regular expressions (or REs) are essentially a tiny, highly specialized programming language. Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to produce bytecode that runs faster. Optimization isn't covered in this document, because it requires that you have a good understanding of the matching engine's internals.
· Generics
o Understanding Generics
Arrays are good for many tasks, but C# v2.0 introduced a new feature called generics. Among many benefits, one huge benefit is that generics allow us to create collections that allow us to do more than allow by an array.
In .NET v1.0 there were collections, such as the ArrayList for working with groups of objects. An ArrayList is much like an array, except it could automatically grow and offered many convenience methods that arrays don't have. The problem with ArrayList and all the other .NET v1.0 collections is that they operate on type object. Since all objects derive from the object type, you can assign anything to an ArrayList. The problem with this is that you incur performance overhead converting value type objects to and from the object type and a single ArrayList could accidentally hold different types, which would cause a hard to find errors at runtime because you wrote code to work with one type. Generic collections fix these problems.
A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it. This eliminates type mismatches at runtime. Another benefit of type safety is that performance is better with value type objects because they don't incur overhead of being converted to and from type object. With generic collections, you have the best of all worlds because they are strongly typed, like arrays, and you have the additional functionality, like ArrayList and other non-generic collections, without the problems.
o Generics and the .NET framework Class Library
Version 2.0 of the .NET Framework class library provides a new namespace, System.Collections.Generic, which includes several ready-to-use generic collection classes and associated interfaces. Other namespaces such as System also provide new generic interfaces such as IComparable. These classes and interfaces are more efficient and type-safe than the non-generic collection classes provided in earlier releases of the .NET Framework. Before designing and implementing your own custom collection classes, consider whether you can use or derive a class from one of the classes provided in the base class library.
System.Collections.Generic namespace contains numerous class and interface types that allow you to contain subitems in a variety of containers.
ICollection
IComparer
IDictionary
IEnumerable
IEnumerator
IList
o Using the LinkedList Generic Class
The System.Collections.Generic namespace also defines a number of "helper" classes and structures that work in conjunction with a specific container. For example, the LinkedListNode type represents a node within a generic LinkedList, the KeyNotFoundException exception is raised when attempting to grab an item from a container using a nonexistent key, and so forth.
Use the generic LinkedList class. The following method creates a LinkedList class, adds nodes to this linked list object, and then uses several methods to obtain information from nodes within the linked list:
public static void UseLinkedList( )
{
   // Create a new LinkedList object.
   LinkedList todoList = new LinkedList( );
 
   // Create TodoItem objects to add to the linked list.
   TodoItem i1 = new TodoItem("paint door", "Should be done third");
   TodoItem i2 = new TodoItem("buy door", "Should be done first");
   TodoItem i3 = new TodoItem("assemble door", "Should be done second");
   TodoItem i4 = new TodoItem("hang door", "Should be done last");
 
   // Add the items.
   todoList.AddFirst(i1);
   todoList.AddFirst(i2);
   todoList.AddBefore(todoList.Find(i1), i3);
   todoList.AddAfter(todoList.Find(i1), i4);
   // Display all items.
   foreach (TodoItem tdi in todoList)
   {
      Console.WriteLine(tdi.Name + " : " + tdi.Comment);
   }
 
   // Display information from the second node in the linked list.
   Console.WriteLine("todoList.First.Next.Value.Name == " 
      + todoList.First.Next.Value.Name);
 
   // Display information from the next to last node in the linked list.
   Console.WriteLine("todoList.Last.Previous.Value.Name == " 
      + todoList.Last.Previous.Value.Name);
}
In the LinkedList class, the previous node is always accessed through the Previous property and the next node is always accessed through the Next property. The first node’s Previous property in the linked list always returns a null value. Likewise, the last node’s Next property in the linked list always returns a null value.
Each node in the linked list is actually a generic LinkedListNode object. So a LinkedList object is actually a collection of LinkedListNode objects. Each of these LinkedListNode objects contains properties to access the next and previous LinkedListNode objects, as well as the object contained within it. The object contained in the LinkedListNode object is accessed through the Value property. In addition to these properties, a LinkedListNode object also contains a property called List, which allows access to the containing LinkedList object.
o System.Collections.ObjectModel
The KeyedCollection, ReadOnlyCollection, and Collection classes are not in the System.Collections.Generic namespace. These classes were moved to the System.Collections.ObjectModel namespace late in the development of version 2.0 of the .NET Framework. The rationale behind this move seemed to come about as a result of concern about creating some confusion for VB developers. The default Microsoft.VisualBasic namespace already included a Collection class, and thus making System.Generics.Collection a default namespace would cause IntelliSense to display two separate collection types for VB developers. To resolve this, the BCL team had the choice of renaming the Collection class or moving it to a new namespace. This is what gave rise to the new System.Collections.ObjectModel namespace.
· Threading
The threads of a computer program allow the program to execute sequential actions or many actions at once. Each thread in a program identifies a process that runs when the program asks it to.
Each process consist of one or more thread. These process can whole or part of the application/ program. A thread is a set of instruction or specific section of application that executes independently within the application or system. This can be also thought as the context in which code runs. So threads are basically light weight processes responsible for multitasking within a single application. Usually OS takes care of scheduling and execution of various threads.
o Need for multithreading
When the system is build on various threads to perform multiple tasks to achieve parallelism and improve the efficiency of the system. This is the ability of any system to do multiple tasks simultaneously. Threads are implementing when there are situations in which more than one task at a time need to be completed.
Some of the benefits of threading are mentioned as follows:
* Using threads the long duration tasks in application can be processed at the background
* User interface can be made more appealing so that there is some task performed during various events like when the user clicks button for the processing some action a progress bar can be shown to show the progress of activity.
* Speed of the application can be increased.
* Threads can be useful in situations where there are gaps between tasks waiting for some event such as user input, file read, or receipt of data over the network. During the situation we can release various precious resources like memory usages etc
o Thread Synchronization
As you write a threaded application, you may need to synchronize individual threads with other parts of your program. Synchronization provides a compromise between the unstructured nature of multithreaded programming and the structured order of synchronous processing.
Thread synchronization requires that a running thread gain a "lock" on an object before it can access it. The thread will wait in line for another thread that is using the method/data member to be done with it. This is very important to prevent the corruption of program data if multiple threads will be accessing the same data. If two threads try to change a variable or execute the same method at the same, this can cause serious and difficult to find problems. Thread synchronization helps prevent this.
o Thread Safety in Windows Forms
Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads. In particular, it must satisfy the need for multiple threads to access the same shared data, and the need for a shared piece of data to be accessed by only one thread at any given time.
· Files and Streams
A stream is an abstraction of a sequence of bytes. This sequence of bytes may come from a file, a TCP/IP socket, or memory. In .NET, a stream is represented, aptly, by the Stream class. The Stream class provides a generic view of a sequence of bytes. A Stream class forms the abstract class of all other streams. That is, you cannot directly create an instance of the Stream class. Instead, the Stream class is implemented by the following classes:
1. BufferedStream: provides a buffering layer on another stream to improve performance.
2. FileStream: provides a way to read and write files.
3. MemoryStream: provides a stream using memory as the backing store.
4. NetworkStream: provides a way to access data on the network.
5. CryptoStream: provides a way to supply data for cryptographic transformation.
Streams fundamentally involve the following operations:
1. Reading
2. Writing
3. Seeking
o Working with Files and Directories
The .NET Framework comes fully equipped with a set of classes to carry out basic file system tasks—creating and reading directories, checking to see if files exist, retrieving file properties, and so on. Most of this magic takes place through two built-in objects, the FileInfo() object and the DirectoryInfo() object, both part of the System.IO namespace.
In this article, I will introduce you to these two objects. I'll show you how to read directories, retrieve file properties, and create a Windows Explorer clone that dynamically generates directory listings and file information.
o The Stream Class
All .NET stream classes are derived from the abstract class System.IO.Stream. Derived classes typically override the properties and methods to read from or write to a particular device. The .NET Framework implements the following stream classes:
* System.IO.FileStream reads and writes files.
* System.IO.MemoryStream can be used to read and write data in memory.
* System.Net.Sockets.NetworkStream is used to read data from and write data to the network, including across the Internet.
* System.Security.Cryptography.CryptoStream links streams to cryptographic transformations.
In addition, System.IO.BufferedStream allows you to compose a buffer around another stream to reduce the number of calls to the operating system and thus increase performance.
A stream is an abstraction of a sequence of bytes, such as you'd read from or write to a file, a network connection, or an I/O device. The Stream class and its derived classes provide a generic view of the data while insulating the programmer from the underlying operating system or particular I/O device.
As pointed out earlier, a stream is a sequence of bytes. All stream operations work in terms of bytes. Length returns the size of the stream in bytes. Read returns the data into an array of bytes, and Write writes data to the stream from an array of bytes. Once you've read data from the stream you can manipulate the array of bytes: converting it to a string or constructing data structures.
The example below reads data from a FileStream into an array of bytes and then converts the data to a String.
o Cryptography
Cryptography is the art and science of keeping messages secure.
When a message is transferred from one place to another, it contents are readily available to an eavesdropper. A simple network-monitoring tool can expose the entire message sent from one computer
to another in a graphical way. For an N-Tier or distributed application to be secure, all messages sent on the network should be scrambled in a way that it is computationally impossible for any one to read it.
In cryptography world the message that needs to be secured is called plaintext or cleartext. The scrambled form of the message is called ciphertext. The process of converting a plaintext to ciphertext is called encryption. The process of reconverting the ciphertext into plaintext is called decryption. Cryptography algorithms (ciphers) are mathematical functions used for encryption and decryptions.
For cryptography to be used in practical solutions algorithms used for encryption and decryption should be made public. This is possible by using a byte stream called Key. For the algorithm to encipher a plaintext to ciphertext and to decipher it back to plaintext it needs Key.
Symmetric Key Encryption
Symmetric key encryption uses same key, called secret key, for both encryption and decryption. Users exchanging data keep this key to themselves. Message encrypted with a secret key can be decrypted only with the same secret key.
Asymmetric Key Encryption
Asymmetric key encryption uses different keys for encryption and decryption. These two keys are mathematically related and they form a key pair. One of these two keys should be kept private, called private-key, and the other can be made public (it can even be sent in mail), called public-key. Hence this is also called Public Key Encryption.
Cryptography in Microsoft .NET
Microsoft.NET has classes that extend the cryptographic services provided by Windows CryptoAPI.
System.Security.Cryptography namespace of Common Language runtime provides classes for
1. Symmetric Key Encryption
2. Asymmetric Key Encryption
3. Hashing
4. Digital Certificates
5. XML Signatures
Symmetric Key Encryption and Asymmetric Key Encryption are discussed in this article. Hashing, Digital Certificates and XML Signatures will be discussed is the subsequent articles.
o Compressions for Stream.Objects
Xceed Streaming Compression for .NET is an ASP component through which compression of data in .NET and ASP.net application can be done. This offers various features like compressing XML data, compressing data to store in the database, helps in continuous use of server, supporting Deflate64T, Deflate, Zlib, Glib format for compressing data and more.
o Serialization
Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or can be continued in a persistent storage location. This storage location can be a physical file, database or ASP.NET Cache. Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines. This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily. The advantage of serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage medium in a non-proprietary format. Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client. De-serialization is the reverse; it is the process of reconstructing the same object later. The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another. In this article I will discuss .NET's support for Serialization and how we can build a class that supports custom serialization.
Serialization in .NET is provided by the System.Runtime.Serialization namespace. This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream. In order to implement serialization in .NET, we basically require a stream and a formatter. While the stream acts as a container for the serialized object(s), the formatter is used to serialize these objects onto the stream.
The basic advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object if required at a later point of time by de-serializing the object. Remoting and Web Services depend heavily on Serialization and De-serialization. Refer to the figure below.
· Exception Handling
o Handling Exceptions
Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. Exceptions are defined as anomalies that occur during the execution of a program. The .NET framework provides a rich set of standard exceptions that are used during exceptions handling. Exception handling is one of the major feature provide by .NET. There might be various reason to handle exception, this can be caused due to improper user inputs, improper design logic or system errors. In this scenario if application do not provide a mechanism to handle these anomalies then there might be cases the application may crash. .NET run time environment provide a default mechanism, which terminates the program execution.
This article provides insight about exception handling on the basis of ASP.NET and C# as code behind.
In ASP.NET exception handling is achieved using the Try ? Catch ? Finally block. All the three are ASP.NET keywords and are used do exception handling. The try block encloses the statements that might throw an exception whereas catch block handles any exception if one exists. The finally block can be used for doing any clean up process. Any general ASP.NET exception forces the application to terminate without allowing the code to continue executing, resulting in an error page.
o Creating Custom Exceptions
Any custom exception you create needs to derive from the System.Exception class. You can either derive directly from it or use an intermediate exception like SystemException or ApplicationException as base class. According to the .NET framework documentation, SystemException is meant only for those exceptions defined by the common language runtime whereas ApplicationException is intended to be used by user code:
public class LoginFailedException: System.Exception
{
}
· Arrays and Collections
Arrays are very useful for holding lots of values under the same name. But there is also something called a Collection that does a similar job. In fact, there's an inbuilt group of Classes in C# specifically for Collections. They can be quite powerful.
With an array, you store data of the same type. So one array can only hold, say, numbers, but not letter. And an array set up as string can't hold numbers. So you can't do this, for example:
arrayPos[0] = 1;
arrayPos[1] = "two";
The first position holds a number and the second position holds text. C# won't let you do this in an array. But you can do it in a collection known as a Hashtable.
Collections can also make it easier to do things like sorting the data in your lists, deleting items, and adding more items. We'll start with the collection class called ArrayLists.
ArrayLists
You use an ArrayList when your collection may need items adding to it, deleting from it, or needs sorting. For example, suppose you are teacher with a class of ten children. You could keep a list of the children's names, add new students, delete ones who leave, and even sort them into brightest and dimmest! If you used a normal array, it would be difficult to do these things.
· Language Integrated Query (LINQ)
Commonly, data is stored in a database, but there are many other forms of accessing and manipulating data as well such as data files, event logs, the Registry, and so forth. Querying and manipulating data is a common part of many applications.
LINQ (often overheard pronounced as "link") is a step in the evolution of data access. It is a programming model that brings a much needed uniformity to accessing data from files, XML, database, registry, event log, and a whole host of other sources of data such as Active Directory and even services from 3rd parties such as Flickr. It is designed to work with all shapes and sizes of different data and allow you to perform Query, Set, and Transform operations on all of it. Pretty much anything that implements IEnumerable is a target for LINQ.
Language-Integrated Query (LINQ) is a new feature introduced in visual studio 2008 and .NET Framework 3.5. Developers can write the queries in the code to retrieve the data from various types of data sources like SQL,XML and XQuery.
Earlier developers has to learn the syntax for writing queries for each data source. LINQ simplifies by offering a model to work with the data across various kinds of data sources.
o LINQ Architecture
By using LINQ you can query and transform the data in
* XML Document
* SQL Databases
* ADO.NET Datasets
* .NET Collections
LINQ Query operation contains three parts
1. Obtain the data source.
2. Create the Query.
3. Execute the Query.
LINQ Example
class LINQExample
{
    static void Main()
    {
        // The Three Parts of a LINQ Query:
        //  1. Data source.
        string[] names = new string[4] { “TOM”, “DAN”, “ADAMS”, “BERNARD” };
 
        // 2. Query creation.
        // nameQuery is an IEnumerable
        var nameQuery =
            from name in names
            where name == “TOM”
            select name;
 
        // 3. Query execution.
        foreach (int name in nameQuery)
        {
            Console.Write("{0,1} ", name);
        }
    }
}
Important thing to notice is when write a query it do not retrieve any data. In order to get the data from data source you need to execute the query.
The data source in the above example is Array and implicitly supports IEnumerable interface. All types that support IEnumerable are called queryable types.
Query expression contains three clauses from, where and select.
The from clause specifies the data source, where clause applies the filter and select clause specifies the types of returned elements.
Query executes in foreach statement in the example. The actual execution of the query starts when iterate over the query variable in foreach statement.
o LINQ to Objects
LINQ to Objects allows .NET developers to write “queries” over collections of objects. Out of the box there is a large set of query operators that provide a similar depth of functionality to what we expect from any SQL language working with a relational database, and if what we need isn’t present out-of-the-box, we can add our own.
Traditionally, working with collections of objects meant writing a lot of looping code using for loops or foreach loops to iterate through a list carrying out filtering using if statements, and some action like keeping a running sum of a total property. LINQ frees you from having to write looping code; it allows you to write queries that filter a list or calculate aggregate functions on elements in a collection as a set.
We can write queries against any collection type that implements an interface called IEnumerable (and also a new interface called IQueryable, but more on that later). This is almost any collection type built into the .NET class libraries including simple arrays like string[], or int[], and any List collection we define. Let us look at a few of the simplest examples to understand the basic syntax.
int[] nums = new int[] {0,4,2,6,3,8,3,1};
var result = from n in nums
where n < 5
orderby n
select n;
foreach(int i in result)
Console.WriteLine(i);
Output:
0
1
2
3
3
4
o LINQ to DataSet
With the introduction of LINQ to DataSet there finally exists a full featured query language for the DataSet. Now your ability to query your data is limited only by CLR, which is no small thing! For an introduction on LINQ to DataSet, please see this post.
This is great new functionality, but for most applications, query is only half of the story. Once you have sliced and diced your data into the form that you want, you need to do something with this data. This might be something as simple as spitting it out to the console, or as complex as binding it to a read/write hierarchical DataGrid. With this wide range of needs comes a wide range of capabilities.
This blog post will talk about how to do data binding with LINQ to DataSet from a high level perspective. Future posts will go into more details on each particular technology, and how to use it in a variety of situations.
If you simply bind the results of a LINQ to DataSet query to a grid (or some other control), you will see the values from your query results. However, the results will be simple values – you will not get the benefits of the DataSet, such as change tracking, transparent updating when the DataSet is updated, etc. Some features may work some of the time, but your experience will be less than stellar.
Why is this? When a LINQ to DataSet query is executed, the result is an IEnumerable. How data binding will work depends on the type of the enumeration (the T). There are a number of possibilities, each with its own problem. If the query is a projection of something, such as anonymous types, then the results are “torn off” from the source DataTable. This means that when you edit the values, then source never gets updated –in essence no data binding is occurring. If the projection is a DataRow, then you will get tracking for those DataRows, but because you are not bound to the DataTable, you end up not being able to add/delete DataRows!
var query = from order in adventureWorksDS1.SalesOrderHeader
where order.IsCreditCardIDNull() == false
orderby order.OrderDate descending
select order;
dataGridView1.DataSource = query.AsDataView();
o LINQ to XML
LINQ to XML is a new way to construct, write and read XML data in the .NET language of the developers’ choice. This new API simplifies working with XML data without having to resort to using additional language syntax like XPath or XSLT. LINQ to XML is not a replacement for any of the current DOM’s or XML class libraries; LINQ to XML in many cases overlaps their functionality and aims to provide a superior developer experience, but existing code will continue to work. One aspect of LINQ to XML is that it supports writing Query Expressions and can be combined with any of the other LINQ technologies to create or use XML data as a source or destination format.
XElement xml = new XElement("contacts",
                    new XElement("contact", 
                        new XAttribute("contactId", "2"),
                        new XElement("firstName", "Barry"),
                        new XElement("lastName", "Gottshall")
                    ),
                    new XElement("contact", 
                        new XAttribute("contactId", "3"),
                        new XElement("firstName", "Armando"),
                        new XElement("lastName", "Valdes")
                    )
                );
 
 
Console.WriteLine(xml);
Out Put:
   contactId="2">
    Barry
    Gottshall
  
   contactId="3">
    Armando
    Valdes
  
o LINQ to SQL
LINQ to SQL allows .NET developers to write “queries” in their .NET language of choice to retrieve and manipulate data from a SQL Server database. In a general sense, LINQ to SQL allows us to create SQL queries in our preferred .NET language syntax and work with a strongly types collection of objects as a return result. We can make changes to these objects then save changes back to the database.
To get an idea of the syntax for LINQ to SQL, we will be using the following SQL database schema. It is a simple software registration and helpdesk. It is populated with sample data and has foreign-key relationships defined where appropriate.
HookedOnLINQ db = 
     new HookedOnLINQ("Data Source=(local);Initial Catalog=HookedOnLINQ"); 
 
   var q = from c in db.Contact
           where c.DateOfBirth.AddYears(35) > DateTime.Now
           orderby c.DateOfBirth descending
           select c;
 
   foreach(var c in q)
       Console.WriteLine("{0} {1} b.{2}",
                   c.FirstName.Trim(),
                   c.LastName.Trim(),c.DateOfBirth.ToString("dd-MMM-yyyy"));
 
Output:
Mack Kamph b.17-Sep-1977
Armando Valdes b.09-Dec-1973