Вы находитесь на странице: 1из 70

OOPS Concepts

OOP is a design philosophy. Everything in OOP is grouped as self sustainable "objects". In order to clearly understand the object orientation, lets take your hand as an example. The hand is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it. Object:

In pure OOP terms an object is an instance of a class. An object can be considered a "thing" that can perform a set of related activities. It is a real time entity. The set of activities that the object performs defines the object's behaviour. For example, the hand can grip something or a Student (object) can give the name or address. Every object is composed by: Object identity: Means that every object is unique and can be differentiated from other objects. Each time and object is created (instantiated) the object identity is defined. Object behavior: What the object can do. In OOP, methods work as functions that define the set of actions that the object can do. Object state: The data stored within the object at any given moment. In OOP, fields, constants, and properties define the state of an object.

Class: A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations. How to identify and design a class: According to OOPS there are 5 principles one needs to follow to design a class SRP: the single responsibility principle o A class should have one, and only one, reason to change. o o o OCP: the open closed principle You should be able to extend a classes behavior, without modifying it. DIP: the dependency inversion principle Derived classes must be substitutable for their base classes. LSP: the liskov substitution principle Depend on abstractions, not on concretions. 1

ISP: the interface segregation principle Make fine grained interfaces that are client specific. Additionally to identify a class correctly,

You need to identify the full list of leaf level functions/ operations of the system (granular level use cases of the system). Then proceed to group each function to form classes (classes will group same types of functions/ operations). However a well defined class must be a meaningful grouping of a set of functions and should support the re-usability while increasing expandability/ maintainability of the overall system. Four main OOPS concepts are Abstraction o Suppression of details o It places the emphasis on what an object is or does rather than how it is represented or how it works. o Abstraction is a process of hiding the implementation details and displaying the essential features. Example for using Abstraction is by Access Specifiers Encapsulation o Hiding information o Encapsulation is a process of binding the data members and member functions into a single unit. o The inclusion within a program object of all the resources need for the object to function - basically, the methods and the data. o In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. Example for encapsulation is by class. Inheritance o Inheritance is a process of deriving the new class from already existing class, by extending it. o It allows you to reuse existing code. o Polymorphism Polymorphism means many forms.

Polymorphism is of two types: Compile time polymorphism/Overloading Runtime polymorphism/Overriding Compile Time Polymorphism

Compile time polymorphism is method and operators overloading. It is also called early binding. 2

In method overloading method performs the different task at the different input parameters. Runtime Time Polymorphism

Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding. When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype. You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing. Things to keep in mind while method overloading If you use overload for method, there are couple of restrictions that the compiler imposes. The rule is that overloads must be different in their signature, which means the name and the number and type of parameters. There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name. Constructors and Destructors: Constructors and destructors are special member functions of classes that are used to construct and destroy class objects.

Framework: It is a platform, which provides you the tools and technology to develop an application.

Dot Net Framework: it provides you the run time and compile time support to develop web / windows applications using CLS compliant languages The .NET Framework is a software framework that runs primarily on Microsoft Windows. Programs written for the .NET Framework execute in a software environment (as contrasted to hardware environment), known as the Common Language Runtime (CLR), an application virtual machine that provides important services such as security, memory management, and exception handling. The class library and the CLR together constitute the .NET Framework. The .NET Framework's Base Class Library provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications. Microsoft also produces a popular integrated development environment largely for .NET software called Visual Studio.


Version Number

Release Date

Visual Studio

Default in Windows

1 1.1 2 3 3.5 4 4.5

1.0.3705.0 1.1.4322.573 2.0.50727.42 3.0.4506.30 3.5.21022.8 4.0.30319.1 4.5.40805

13-02-2002 24-04-2003 07-11-2005 06-11-2006 19-11-2007 12-04-2010 29-02-2012

Visual Studio .NET

Visual Studio .NET 2003 Visual Studio 2005

Windows XP Tablet and Media Center Editions Windows Server 2003 Windows Server 2003 R2 Windows Vista, Windows Server 2008 Windows 7, Windows Server 2008 R2 Windows 7(Recommended) Windows 8, Windows Server 8

Visual Studio 2008 Visual Studio 2010 Visual Studio '11'

.Net Execution flow:

Managed code: Code that is executed by the CLR is sometimes referred to as "managed

Unmanaged code: Code which is compiled into native machine language that targets a
specific system is referred to as Un-managed code. Framework Class Library: It is a collection of large number of language independent, type-safe, re-usable classes. The classes are divided into logical grouping called Namespaces The classes allow the application to use system services The root namespace is : System Common Language Specification:

o o

It defines a small set of specification that each language should follow in order to be .Net compliant language. o No global function declaration o No pointers o No multiple inheritances

It enables inter-operability among applications even when they are created using different languages.

Common Type System:

The CTS defines the predefined data types that are available in IL, so that all languages that target the .NET Framework will produce compiled code that is ultimately based on these types. It is the set of rules that the compiler must follow, in order to define, use and store data types. o For the previous example, Visual Basic 2009s Integer is actually a 32-bit signed integer, which maps exactly to the IL type known as Int32. This will therefore be the data type specified in the IL code. Because the C# compiler is aware of this type, there is no problem. At source code level, C# refers to Int32 with the keyword int, so the compiler will simply treat the Visual Basic 2009 method as if it returned an int.

Garbage collector:

Up until now, two techniques have been used on the Windows platform for de-allocating memory that processes have dynamically requested from the system: Make the application code do it all manually. Make objects maintain reference counts. used in COM; The idea is that each COM component maintains a count of how many clients are currently maintaining references to it. When this count falls to zero, the component can destroy itself and free up associated memory and resources. The garbage collector runs as a low priority thread in the background that keeps track of unreferenced objects (objects that are no longer referenced by) by marking them as dirty objects. 6

Namespace: System.GC System.GC.Collect() :- allows us to start garbage collection when we require. However it is best to leave garbage collection to run time. Before removing the object, the garbage collector calls the Finalize() method or destructor of the object. Implementing IDispose interface to your class and override the Dispose() method. Class GarbageCollection : IDisposable { Public void Dispose () { GC.SuppressFinalize(this); } } Assemblies: It is the fundamental unit of deployment, version control, security and re-use It contains code that the common language runtime executes An assembly can contain classes, structures, interfaces, and resources that an application requires. When we compile a program, the compiler translates the source code into the Intermediate Language code (IL) Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. It forms a type boundary. Every type's identity includes the name of the assembly in which it resides. A type called My-Type loaded in the scope of one assembly is not the same as a type called My-Type loaded in the scope of another assembly. Versioning is done only on Assemblies with strong name. Format of Assembly version:
<major version>.<minor version>.<build number>.<revision>

Security consideration in Assembly: When you build an assembly, you can specify a set of permissions that the assembly requires to run. Whether certain permissions are granted or not granted to an assembly is based on evidence. Assemblies are designed to simplify application deployment and Solve versioning problems that can occur with component-based applications. Assembly types:

Assemblies can be static or dynamic. 7

Static assemblies are stored on disk in portable executable (PE) files.

Dynamic assemblies run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Dynamic assemblies can be created by System.Reflection.Emit Namespace The System.Reflection.Emit namespace contains classes that allow a compiler or tool to emit metadata and Microsoft intermediate language (MSIL) and optionally generate a PE file on disk. The primary clients of these classes are script engines and compilers. Assemblies can be shared and private o Shared assemblies are used by more than one application A shared assembly is installed in the Global Assembly Cache: GAC: - is nothing but a special disk folder where all the shared assemblies are

kept. It is located under <drive>:\Windows\Assembly folder on every machine running the .NET framework. o It is a machine-wide code cache Once your application installs Assemblies in the GAC, it loses the benefits of

XCOPY deployment as these assemblies (other than the .NET System Libraries) must be explicitly installed in the GAC. Private assembly is used by a single application. Private assemblies are installed in a directory named \bin located under the Suppose we have created a DLL which encapsulates business logic. This DLL is

application directory. used by the client application only and not by any other application. In order to run the application properly the DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to the application Contents of Assembly:

In general, a static assembly can consist of four elements: The assembly manifest, which contains assembly metadata. Type metadata. Microsoft intermediate language (MSIL) code that implements the types. A set of resources.

The files that make up a multi-file assembly are not physically linked by the file system. Rather, they are linked through the assembly manifest and the common language runtime manages them as a unit. Assembly Manifest:

The following table shows the information contained in the assembly manifest. The first four itemsthe assembly name, version number, culture, and strong name information make up the assembly's identity.
Information Assembly name Version number Description A text string specifying the assembly's name. A major and minor version number, and a revision and build number. The common language runtime uses these numbers to enforce version policy. Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a satellite assembly.)


Strong name The public key from the publisher if the assembly has been given a strong information/ public key name. info List of all files in the assembly A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest. Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.

Type reference Information

Information on A list of other assemblies that are statically referenced by the assembly. referenced assemblies Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.

Strong Name Assemblies: A strong name consists of the assembly's identity simple text name, version number, culture information (optional) public key (optional):- used to guarantee name uniqueness and to protect the name from unwanted reuse And a digital signature.

It is generated from an assembly file (the file that contains the assembly manifest, which in turn contains the names and hashes of all the files that make up the assembly), using the corresponding private key. Microsoft Visual Studio .NET and other development tools provided in the Windows Software Development Kit (SDK) can assign strong names to an assembly. Assemblies with the same strong name are expected to be identical.

You can ensure that a name is globally unique by signing an assembly with a strong name. In particular, strong names satisfy the following requirements: o Strong names guarantee name uniqueness by relying on unique key pairs. No one can generate the same assembly name that you can, because an assembly generated with one private key has a different name than an assembly generated with another private key. o Strong names protect the version lineage of an assembly. A strong name can ensure that no one can produce a subsequent version of your assembly. Users can be sure that a version of the assembly they are loading comes from the same publisher that created the version the application was built with. o Strong names provide a strong integrity check. Passing the .NET Framework security checks guarantees that the contents of the assembly have not been changed since it was built. Note, however, that strong names in and of themselves do not imply a level of trust like that provided, for example, by a digital signature and supporting certificate. When you reference a strong-named assembly, you expect to get certain benefits, such as versioning and naming protection. If the strong-named assembly then references an assembly with a simple name, which does not have these benefits, you lose the benefits you would derive from using a strong-named assembly and revert to DLL conflicts. Therefore, strong-named assemblies can only reference other strong-named assemblies. How the Runtime Locates Assemblies: Deployment Scenarios for .NET Framework Applications Step 1: Examining the Configuration Files Step 2: Checking for Previously Referenced Assemblies Step 3: Checking the Global Assembly Cache Step 4: Locating the Assembly through Codebases or Probing Partial Assembly References

The runtime uses the following steps to resolve an assembly reference: Determines the correct assembly version by examining applicable configuration files, including the application configuration file, publisher policy file, and machine configuration file. If the configuration file is located on a remote machine, the runtime must locate and download the application configuration file first. Checks whether the assembly name has been bound to before and, if so, uses the previously loaded assembly. If a previous request to load the assembly failed, the request is failed immediately without attempting to load the assembly. Checks the global assembly cache. If the assembly is found there, the runtime uses this assembly. Probes for the assembly using the following steps: a. If configuration and publisher policy do not affect the original reference and if the bind request was created using the Assembly.LoadFrom method, the runtime checks for location hints. 10

b. If a code base is found in the configuration files, the runtime checks only this location. If this probe fails, the runtime determines that the binding request failed and no other probing occurs. c. Probes for the assembly using the heuristics described in the probing section. If the assembly is not found after probing, the runtime requests the Windows Installer to provide the assembly. This acts as an install-on-demand feature. Note: There is no version checking for assemblies without strong names, nor does the runtime check in the global assembly cache for assemblies without strong names. Initiating the binding:

The process of locating and binding to an assembly begins when the runtime attempts to resolve a reference to another assembly. This reference can be either static or dynamic. The compiler records static references in the assembly manifest's metadata at build time. Dynamic references are constructed on the fly as a result of calling various methods, such as System.Reflection.Assembly.Load. The preferred way to reference an assembly is to use a full reference, including the assembly name, version, culture, and public key token (if one exists). The runtime uses this information to locate the assembly, following the steps described later in this section. The runtime uses the same resolution process regardless of whether the reference is for a static or dynamic assembly. You can also make a dynamic reference to an assembly by providing the calling method with only partial information about the assembly, such as specifying only the assembly name. In this case, only the application directory is searched for the assembly, and no other checking occurs. You make a partial reference using any of the various methods for loading assemblies such as System.Reflection.Assembly.Load or System.AppDomain.Load. Finally, you can make a dynamic reference using a method such as System.Reflection.Assembly.Load and provide only partial information; you then qualify the reference using the <qualifyAssembly> element in the application configuration file. This element allows you to provide the full reference information (name, version, culture and, if applicable, the public key token) in your application configuration file instead of in your code. You would use this technique if you wanted to fully qualify a reference to an assembly outside the application directory, or if you wanted to reference an assembly in the global assembly cache but you wanted the convenience of specifying the full reference in the configuration file instead of in your code.

Module: A module is a logical collection of code within an Assembly. You can have multiple modules inside an Assembly, and each module can be written in different .NET languages (VS, as far as I'm aware, doesn't support creation of multi-module assemblies).


Assemblies functions.








Yes you can access assemblies, modules, classes, functions, properties, fields etc all via reflection at runtime. The MSDN states that: "A module is a Microsoft intermediate language (MSIL) file that does not have an assembly manifest. Module: A single file containing content that can be executed by the VES DLL Hell Problem:

Windows Registry cannot support the multiple versions of same com component this is called the Dll hell problem. Dll Hell refers to a set of problems caused when multiple applications attempt to share a common component like a dynamic link library (DLL). The reason for this issue was that the version information about the different components of an application was not recorded by the system.
DLL Hell: - This is a problem in loading a specific Dll (class id, version number,

path etc). For example, if I build test.dll v1.0.0.0 and deploying it in c:\MyProg. My application App1 and App2 are using the methods in that Dll. And there is a requirement to change something in App1 and I supposed to change test.dll also for the same requirement. Once I finished with all my changes, I will be deploying them in the appropriate locations. Now, the older Dll will be overwritten. And my App2 will look for test.dll of older version and since it is not there it will not work. This is a scenario for Dll hell issue. Dll hell problem is solved by dotnet it allows the application to specify not only the library it needs to run but also the version of the assembly. .Net Framework provides operating systems with a Global Assembly Cache. This Cache is a repository for all the .Net components that are shared globally on a particular machine. When a .Net component is installed onto the machine, the Global Assembly Cache looks at its version, its public key, and its language information and creates a strong name for the component. The component is then registered in the repository and indexed by its strong name, so there is no confusion between different versions of the same component, or DLL.
.NET and Dll hell: - .NET has a provision to specify whether a 'Specific Version' to

be loaded or not. If you check with any dll's property window, that has a property called Specific Version. By default it will be false for the dll's created by users. It means whether the specific version alone has to be loaded for that project. If that is false, then the runtime will load any available higher version of dll for that project. Thus this issue has been sorted out.

Pre-Defined Data Type: 12

Two categories of data type: Value types:- stored in stack :: derived from System.ValueType o Built-in types Built in types are the base types provided by the dot net framework. All other types are derived from this The run time optimizes the performance for 32 bit integers. For floating type values use double. All types are derived from System.Object. o User defined types Also known as structures or structs Structs (C#) or Structures (VB) are usually more efficient than classes. They are light weight objects and perform efficiently when amount of data is less. Enumerations Related symbols with a defined value. It is used to enhance the code readability and simplify coding. It enhances code readability by replacing the variable values with meaningful words.

Reference types: - store the address of their data Pointers (address of the data) are stored in stack and Values (actual values) stored in managed heap. More than 2500 reference types Common reference types are System.Object System.String:- used to create immutable strings; inherits some functionalities from System.Object like +,&,<>,!=etc For ex: String s = a S+=b => ab S+=c=> abc S+=d=>abcd Only the last string would contain the reference all other instances would be disposed by the garbage collector.

Immutable string: when any change is done to the string, during runtime, new object is created to store the modified string, while the old string objects are abandoned. System.Text.StringBuilder :- used to create dynamic mutable strings. The default constructor creates a buffer of size 16 bytes long, which grows as needed. System.Array System.Exception System.IO.Stream

C# Type

.NET Framework Type




Byte Sbyte Char Decimal Double Float Int Uint Long Ulong Object Short Ushort String

System.Byte System.SByte System.Char System.Decimal System.Double System.Single System.Int32 System.UInt32 System.Int64 System.UInt64 System.Object System.Int16 System.UInt16 System.String

Boxing & Un-boxing: Boxing: Value type Reference type Ex: int j = 0; object obj= (int) j; Un-Boxing: Reference type Value type Ex : object obj = 123 Type conversion: Narrowing: destination size < source size Widening: destination size > source size

VB implements implicit type conversion C# allows implicit type conversion, only for widening type conversions

Namespace: Provide a way to organize classes and types. Namespace is a logical grouping not physical grouping. Main method (): Execution Entry point of a C# programs Must be a static method of a class (or struct), and must have a return type of either int or void. Main method is usually marked as Public; however we can keep the accessibility level as Private also. One class can contain only one Main method() However you can have multiple Main method () in your programs; BUT you need to specify which main method needs to be invoked first. This is done by /main switch Ex: csc MyProgram.cs /main:Namespace:Class Parameters to the Main () String [] is the parameter that can be sent to main method from the command line. For ex: csc Myprogram.cs /a/b/c 14

Classes and Structs:

Access Modifiers: Meaning Access is not restricted. Access is limited to the containing class or types derived from the containing class. Access is limited to the current assembly.

Declared accessibility Public Protected Internal

protectedintern Access is limited to the current assembly or types derived from al the containing class. Private Access is limited to the containing type.

Only one access modifier is allowed for a member or type, except when you use the protectedinternal combination. Access modifiers are not allowed on namespaces. Namespaces have no access restrictions. Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal. Nested types, which are members of other types, can have declared accessibilities as indicated in the following table. Members of Enum Class Default member accessibility Public Private Allowed declared accessibility of the member None Public protected internal private protectedinternal None public internal private

Interface Struct

Public Private

Modifiers are used to modify declarations of types and type members. This section introduces the C# modifiers:


Purpose 15

Access Modifiers public private internal protected Abstract Const Event Extern New Override Partial Readonly Sealed Static Unsafe Virtual Volatile

Specify the declared accessibility of types and type members.

Indicates that a class is intended only to be a base class of other classes. Specify Specifies that the value of the field or the local variable cannot be modified. Declares an event. Indicates that the method is implemented externally. Hides an inherited member from a base class member. Provides a new implementation of a virtual member inherited from a base class. Defines partial classes and structs throughout the same assembly. Declares a field that can only be assigned values as part of the declaration or in a constructor in the same class. Specifies that a class cannot be inherited. Declares a member that belongs to the type itself instead of to a specific object. Declares an unsafe context. Declares a method or an accessor whose implementation can be changed by an overriding member in a derived class. Indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

Partial: It allow for the definition of a class, struct, or interface or method to be split across multiple files The benefit of this approach is that it hides the details of the class definition so that the derived class can focus on the significant portion of the definition.
When working on large projects, spreading a class over separate files enables

multiple programmers to work on it at the same time.

When working with automatically generated source, code can be added to the

class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.
The partial modifier is not available on delegate or enumeration declarations. All partial type definitions that are meant to be of same type must be spanned

in a single assembly / module (.exe or .dll). They should not be spanned across multiple assembly / module 16

Example://BigClassPart1.cs partial class TheBigClass q{ public void MethodOne() {} } //BigClassPart2.cs partial class TheBigClass { public void MethodTwo() {} }

When the project that these two source files are part of is compiled, the output is
partial class TheBigClass { public void MethodOne() {} public void MethodTwo() {} }

If any of the following keywords are used in describing the class, the same must apply to all partials of the same type: public private protected internal abstract sealed base class new generic constraints Partial Methods: A partial class or struct may contain a partial method A partial method declaration contains Definition

o Implementation: this can be done in the same part or in another part of the partial class

If the implementation is not supplied, then the method and all calls to the method are removed at compile time. No compile-time or run-time errors will result if the method is called but not implemented. Partial method declarations must begin with the contextual keyword partial and the method must return void. Partial methods can have ref but not out parameters. Partial methods are implicitly private, and therefore they cannot be virtual. Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.

Partial methods can have static and unsafe modifiers. Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one. You cannot make a delegate to a partial method.
Generics: Generics introduce the concept of type parameters to the .NET Framework The concept behind generics is parametric polymorphism. By using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations. By creating a generic class, you can create a collection that is type-safe at compile-time. Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes. Generics do not create run time error by type casting wrong data types It is faster compared to casting, since it doesnt require Boxing and un-boxing. Classes and Structs: They are templates from which you can create objects (instances)




They are light weight objects and are similar to classes. They can be instantiated in 3 ways Using the new keyword and calling the default no-argument constructor. Using the new keyword and calling a custom or user defined constructor. Without using the new keyword.
struct Point { public double x; public double y; public Point(int x, int y) { this.x = x; this.y = y; }


public override string ToString() { return "(" + x + ", " + y + ")"; } }

As we mentioned earlier, we cannot provide the no-argument constructor in a struct and if we try to do so, the compiler will generate an error. The compiler implicitly provides a default no-argument constructor for each struct which initializes the fields of a struct with their default values. In the following Main() method.
class Test { static void Main() { Point pt = new Point(); Point pt1 = new Point(15, 20); Point pt2; pt2.x = 6; pt2.y = 3; // instantiation without using the new keyword Console.WriteLine("pt = {0}", pt); Console.WriteLine("pt1 = {0}", pt1); Console.WriteLine("pt2 = {0}", pt2); } }

Structs have the following properties: Structs are value types and classes are reference types. Unlike classes, structs can be instantiated without using a new operator. Structs can declare constructors, but they must take parameters. A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object. A struct can implement interfaces. A struct can be used as a nullable type and can be assigned a null value. Within a struct declaration, fields cannot be initialized unless they are declared as const or static. A struct may not declare a default constructor (a constructor without parameters) or a destructor.

Difference between Structure and Class: Structs differ from Classes by o Structs are value types o Classes are reference types o o o o Structs dont support inheritance Classes support inheritance (they implement interface) Classes are used for large amount of data Structs are used for small amount of data 19

o o

By default class members are private By default all Structs members are public

Class members: 1. Data members: contain data for the class 2. Function members: manipulate data for the class Methods: o Instantiated / Concrete methods o Static methods Properties: o Property = field + method o Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. o Properties can be used as if they are public data members, but they are actually special methods called accessors. o Properties are declared in the class block by specifying the access level of the field, followed by the type of the property, followed by the name of the property, and followed by a code block that declares a get-accessor and/or a set accessor

< access modifier> <data type> <name of property> { get { // some optional statements return <some private field>; } set { // some optional statements; <some private field> = value; } }
class TimePeriod { private double seconds; public double Hours { get { return seconds / 3600; } set { seconds = value * 3600; } } } class Program { static void Main() { TimePeriod t = new TimePeriod(); // Assigning the Hours property causes the 'set' accessor to be called. t.Hours = 24; // Evaluating the Hours property causes the 'get' accessor to be called. System.Console.WriteLine("Time in hours: " + t.Hours); } }


Properties are context sensitive. o If the compiler sees that the property Name is on the left hand side of assignment operator, it will call the set { } o If the compiler sees that the property Name is on the right hand side of assignment operator, it will call the get{ }

An abstract property declaration does not provide an implementation of the property accessors. Only declaration no definition. The class that inherits the properties can implement the property according to their own requirement. Return type of Get accessor = Return type of Property

The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property. When you assign a value to the property, the set accessor is invoked by using an argument that provides the new value. Properties can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers. For example, the get may be public to allow read-only access from outside the type, and the set may be private or protected. A property may be declared as a static property by using the static keyword. This makes the property available to callers at any time, even if no instance of the class exists. A property may be marked as a virtual property by using the virtual keyword. This enables derived classes to override the property behavior by using the override keyword. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual. Lastly, a property can be declared abstract. This means that there is no implementation in the class, and derived classes must write their own implementation. Indexers:

Indexers provide a way to access a class or struct in the same way as an array Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set {


arr[i] = value; } } } // This class shows how client code uses the indexer class Program { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = "Hello, World"; System.Console.WriteLine(stringCollection[0]); } }

New Modifier When New is used as an Access modifier, it is used to hide a member that is inherited from the base class. When you hide an inherited member, the derived version of the member replaces the base-class version. Although you can hide members without the use of the new modifier, the result is a warning. It is an error to use both new and override on the same member because the two modifiers have mutually exclusive meanings. The new modifier creates a new member with the same name and causes the original member to become hidden. The override modifier extends the implementation for an inherited member. Hidden members can be accessed by their fully qualified names viz., BaseClassName.HiddenMemberName Keyword new can be used with keyword virtual also.

If keyword override is used in derive class then its override the parent method. If Keyword new is used in derive class then derive method hided by parent method. Abstract: it does not contain implementation

Can be used on method, property, indexers, class, structs and events Abstract class have the following features: When used with class an Abstract class must be used as a base class and the derived class must implement the members marked as abstract. An abstract class cannot be instantiated. 22

An abstract class may contain abstract methods and accessors. It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited. A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors. The abstract classes are not allowed to instantiate the class. So use the protected constructor rather than using public constructor. Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation. Abstract methods have the following features: An abstract method is implicitly a virtual method. Abstract method declarations are only permitted in abstract classes. Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature. The implementation is provided by an overriding method override, which is a member of a non-abstract class. declaration.
However you can also have virtual methods defined in an abstract class. The

It is an error to use the static or virtual modifiers in an abstract method

virtual method may have its default implementation, where a subclass can override it when required. Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax. It is an error to use the abstract modifier on a static property.
An abstract inherited property can be overridden in a derived class by including

a property declaration that uses the override modifier. An abstract class must provide implementation for all interface members. An abstract class that implements an interface might map the interface methods onto abstract methods. For example:
interface I { void M(); } abstract class C: I { public abstract void M(); }



An interface can be a member of a namespace or a class and can contain signatures of the following members: o Methods o Properties o Indexers o Events o Delegates The implementation of the methods is done in the class that implements the interface, as shown in the following example:
Code Sample
interface ISampleInterface { void SampleMethod(); } class ImplementationClass : ISampleInterface { // Explicit interface member implementation: void ISampleInterface.SampleMethod() { // Method implementation. } static void Main() { // Declare an interface instance. ISampleInterface obj = new ImplementationClass(); // Call the member. obj.SampleMethod(); } }

An interface can inherit from one or more base interfaces. When a base type list contains a base class and interfaces, the base class must come first in the list. A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface. It provides a set of members to the class that implements the interface. Interfaces describe a group of related functionalities that can belong to any class or struct. Interfaces can consist of methods, properties, events, indexers, or any combination of those four member types. An interface cannot contain fields. Interfaces members are automatically public. An interface contains only the signatures of Methods Properties Events Indexer An interface can inherit from one or more base interfaces. Thereby implementing multiple inheritance concept. When a base type list contains a base class and interfaces, the base class must come first in the list. 24

Sample Interface program

// keyword_interface_2.cs // Interface implementation using System; interface IPoint { // Property signatures: int x { get; set; } int y { get; set; } } class Point : IPoint { // Fields: private int _x; private int _y; // Constructor: public Point(int x, int y) { _x = x; _y = y; } // Property implementation: public int x { get { return _x; } set { _x = value; } } public int y { get { return _y; } set { _y = value; } } } class MainClass { static void PrintPoint(IPoint p) { Console.WriteLine("x={0}, y={1}", p.x, p.y); } static void Main() {


Point p = new Point(2, 3); Console.Write("My Point: "); PrintPoint(p); } }

My Point: x=2, y=3

When two Interfaces have a 2 method that have same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation
2 methods but same signature
interface IControl { void Paint(); } interface ISurface { void Paint(); } class SampleClass : IControl, ISurface { // Both ISurface.Paint and IControl.Paint call this method. public void Paint() { } }

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences. What is an Abstract Class? An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards. What is an Interface? An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. Since C# doesnt support multiple inheritance, interfaces are used to implement multiple inheritance. Both Together When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface. 26

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes. Difference between Interface and Abstract class Feature Multiple inheritance Default implementation Interface A class may inherit several interfaces. An interface cannot provide any code, just the signature. Abstract class A class may inherit only one abstract class. An abstract class can provide complete, default code and/or just the details that have to be overridden. An abstract class can contain access modifiers for the subs, functions, properties

Access Modifiers

An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. If various implementations only share method signatures then it is better to use Interfaces. Requires more time to find the actual method in the corresponding classes. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. No fields can be defined in interfaces 27

Core VS Peripheral

An abstract class defines the core identity of a class and there it is used for objects of the same type. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use. Fast



Adding functionality (Versioning)

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. An abstract class can have fields and

Fields and Constants



Abstract class constants defined

Difference between Interface and Abstract Class Interfaces are closely related to abstract classes that have all members abstract. For an abstract class, at least one method of the class must be an abstract method that means it may have concrete methods. For an interface, all the methods must be abstract Class that implements an interface much provide concrete implementation of all the methods definition in an interface or else must be declare an abstract class In C#, multiple inheritance is possible only through implementation of multiple interfaces. Abstract class can only be derived once. An interface defines a contract and can only contains four entities viz methods, properties, events and indexes. An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types. Also an interface cannot contain static members of any kind. The modifiers abstract, public, protected, internal, private, virtual, override is disallowed, as they make no sense in this context. Class members that implement the interface members must be publicly accessible.

There are quite a big difference between an interface and an abstract class, even though both look similar. Interface definition begins with a keyword interface so it is of type interface Abstract classes are declared with the abstract keyword so it is of type class Interface has no implementation, but they have to be implemented. Abstract classs methods can have implementations and they have to be extended.

Interfaces can only have method declaration (implicitly public and abstract) and fields (implicitly public static) Abstract classs methods cant have implementation only when declared abstract.

Interface can inherit more than one interfaces Abstract class can implement more than one interfaces, but can inherit only one class

Abstract class must override all abstract method and may override virtual methods Interface can be used when the implementation is changing

Abstract class can be used to provide some default behavior for a base class.


Interface makes implementation interchangeable Interface increase security by hiding the implementation Abstract class can be used when implementing framework

Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies. Virtual:
The virtual keyword is used to modify a method, property, indexer and event,

so that it can be overridden in the derived class

By default, methods are non-virtual. You cannot override a non-virtual method. You cannot use the virtual modifier with the static, abstract, private, or

override modifiers.
It is an error to use the virtual modifier on a static property. A virtual inherited property can be overridden in a derived class by including a

property declaration that uses the override modifier.

If parent method is marked by keyword Virtual but child is not marked by

keyword override, then program will compile but the parent method will not be overrided.
If Child method is marked by keyword override but parent method is not

marked by keyword virtual then program will not compile. It will give following error: OOPS_Concept.TestB.display(): cannot override inherited member OOPS_Concept.TestA.display() because it is not marked virtual, abstract, or override. Sealed: - A sealed class cannot be inherited.
The keyword sealed prevents inheritance of those members that were earlier

declared virtual.
A sealed class cannot be used as a base class. Method cant be sealed directly. When applied to a method or property, the sealed modifier must always be

used with override.

Methods of only derived class can be made sealed with keyword sealed and

override. Versioning using New and Override keyword:

In C#, derived classes can contain methods with the same name as base class methods. The base class method must be defined virtual.
If the method in the derived class is not preceded by new or override keywords,

the compiler will issue a warning and the method will behave as if the new keyword were present. 29

If the method in the derived class is preceded with the new keyword, the

method is defined as being independent of the method in the base class.

If the method in the derived class is preceded with the override keyword,

objects of the derived class will call that method instead of the base class method.
The base class method can be called from within the derived class using the

base keyword.
The override, virtual, and new keywords can also be applied to properties,

indexers, and events. By default, C# methods are not virtual. If a method is declared as virtual, any class inheriting the method can implement its own version. To make a method virtual, the virtual modifier is used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class. For more information, see Compiler Warning (level 2) CS0108. Override and Method Selection

When a method is named on a class, the C# compiler selects the best method to call if more than one method is compatible with the call, such as when there are two methods with the same name, and parameters that are compatible with the parameter passed. The following methods would be compatible: C# public class Derived : Base { public override void DoWork(int param) { } public void DoWork(double param) { } } When DoWork is called on an instance of Derived, the C# compiler will first try to make the call compatible with the versions of DoWork declared originally on Derived. Override methods are not considered as declared on a class, they are new implementations of a method declared on a base class. Only if the C# compiler cannot match the method call to an original method on Derived will it try to match the call to an overridden method with the same name and compatible parameters. For example: C# int val = 5; Derived d = new Derived(); d.DoWork(val); // Calls DoWork(double).


Because the variable val can be converted to a double implicitly, the C# compiler calls DoWork(double) instead of DoWork(int). There are two ways to avoid this. First, avoid declaring new methods with the same name as virtual methods. Second, you can instruct the C# compiler to call the virtual method by making it search the base class method list by casting the instance of Derived to Base. Because the method is virtual, the implementation of DoWork(int) on Derived will be called. For example: C# ((Base)d).DoWork(val); // Calls DoWork(int) on Derived. Static classes:

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class Static members belong to the whole class rather than to individual object. Static members are accessed with the name of class rather than reference to objects Following are the main features of a static class: They only contain static members; non-static members cant be used inside a static class. (however static members can be accessed from non-static classes) They cannot be instantiated. They are sealed. They cannot contain Instance Constructors. Static constructors are called even before the class is instantiated. Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. 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. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor. A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for example, a math library might contain static methods for calculating sine and cosine. Static methods can be overloaded but not overridden. Static constructors have the following properties:
A static constructor does not take access modifiers or have parameters. A static constructor is called automatically to initialize the class before the first

instance is created or any static members are referenced.

A static constructor cannot be called directly. The user has no control on when the static constructor is executed in the

program. 31

A typical use of static constructors is when the class is using a log file and the

constructor is used to write entries to this file.

Static constructors are also useful when creating wrapper classes for

unmanaged code, when the constructor can call the LoadLibrary method. A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced. Collections:

Collections are classes that allow you to store, look-up and iterate over collection of related objects. Class
Class ArrayList Description Implements the IList interface using an array whose size is dynamically increased as required. Manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0). Compares two objects for equivalence, ignoring the case of strings.



CaseInsensitiveHashCodePr Obsolete. Supplies a hash code for an object, using a ovider hashing algorithm that ignores the case of strings. CollectionBase Provides the abstract base class for a strongly typed collection. Compares two objects for equivalence, where string comparisons are case-sensitive. Provides the abstract base class for a strongly typed collection of key/value pairs. Represents a collection of key/value pairs that are organized based on the hash code of the key. Represents a first-in, first-out collection of objects. Provides the abstract base class for a strongly typed nongeneric read-only collection. Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index. Represents a simple last-in-first-out (LIFO) non-generic collection of objects.




Queue ReadOnlyCollectionBase



Structure DictionaryEntry Description Defines a dictionary key/value pair that can be set or retrieved.


Interface ICollection Description Defines size, enumerators, and synchronization methods for all nongeneric collections. Exposes a method that compares two objects. Represents a nongeneric collection of key/value pairs.

IComparer IDictionary

IDictionaryEnumer Enumerates the elements of a nongeneric dictionary. ator IEnumerable Exposes the enumerator, which supports a simple iteration over a nongeneric collection. Supports a simple iteration over a nongeneric collection.


IEqualityComparer Defines methods to support the comparison of objects for equality. IHashCodeProvide Obsolete. Supplies a hash code for an object, using a custom hash r function. IList Represents a non-generic collection of objects that can be individually accessed by index.

Array List: public class ArrayList : IList, ICollection, IEnumerable, ICloneable 33

ArrayList accepts a null reference (Nothing in Visual Basic) as a valid value and Allows duplicate elements. If Count already equals Capacity, the capacity of the ArrayList is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added. The capacity of a ArrayList is the number of elements the ArrayList can hold. As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly. Declaration ArrayList <array name> = new ArrayList () To add item Add (): used to add a single item into the ArrayList o o Parameters: i/p: object Output: index

AddRange(): used to add a range of items from any object that implements ICollection interface into the ArrayList Source an object that implements ICollection interface ex:- all Arrays, ArrayList and other collection members Destination Parent ArrayList Both the above methods insert data at the End of the collection. To insert an item Insert () InsertRange() The above methods insert a new object / range of objects at the given index, while the current element at the given index is shifted to the next position. For ex: Arr[1]= hi Arr[2]=how Arr[3]=are u Arr.Insert (2,hello) Output: Arr[1]=hi Arr[2]=hello Arr[3]=how Arr[4]=are u New elements can be inserted into an ArrayList using the index positions. But when compared to insert methods, this method removes the element at the given index and inserts the new element. 34

Insert using index remove element @given index insert the new element @the given index. To remove elements: Remove () RemoveAt() RemoveRange() Iterating through an ArrayList:

1. Using for Loop and using the count property of the ArrayList. 2. Using foreach loop 3. ArrayList implements IEnumerator interface. It has a method called GetEnumerator, which returns the Enumerator (IEnumerator interface) for the given set of elements. IEnumerator has 2 methods: 1. MoveNext: - goes only in forward direction 1 property: Current: - gets the current item. Using IEnumerator allows us to iterate through the ArrayList in an orderly fashion.
IEnumerator ie = arr.GetEnumerator(); while (ie.MoveNext ()) { Console .WriteLine ( ie.Current); }


Consistent Interfaces in the Collection list:

IEnumerator: - Provide a common way to iterate over a collection ICollection: - Provides a definition for how the collections API should look. Provides a common way to add items and copy the collections into an array ICollection derives from IEnumerator. IList: Provides a way to expose a list of item. Derived directly from ICollections.
Sort Method: Used to sort the items in a collection of homogeneous objects. It is better to use the custom class that implements IComparer interface and perform the sorting. The IComparer interface exposes a method called int Compare (object x, object y) Inside this method create an object of CaseInsensitiveComparer class and use the Compare method
class DescendingComparer : IComparer { private CaseInsensitiveComparer _comparer = new CaseInsensitiveComparer();


public int Compare(object x, object y) { return _comparer.Compare(y, x); } }

List (T) Generic class:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable

It represents a strongly typed list of objects that can be accessed via index. Provides features to search, sort and manipulate the list of objects. It is the generic equivalent of the ArrayList class

Performance Considerations

In deciding whether to use the List(T) or ArrayList class, both of which have similar functionality, remember that the List(T) class performs better in most cases and is type safe. If a reference type is used for type T of the List(T) class, the behaviour of the two classes is identical. However, if a value type is used for type T, you need to consider implementation and boxing issues. If a value type is used for type T, the compiler generates an implementation of the List(T) class specifically for that value type. That means a list element of a List(T) object does not have to be boxed before the element can be used, and after about 500 list elements are created the memory saved not boxing list elements is greater than the memory used to generate the class implementation. Make certain the value type used for type T implements the IEquatable(T) generic interface. If not, methods such as Contains must call the Object.Equals(Object) method, which boxes the affected list element. If the value type implements the IComparable interface and you own the source code, also implement the IComparable(T) generic interface to prevent the BinarySearch and Sort methods from boxing list elements. If you do not own the source code, pass an IComparer(T) object to the BinarySearch and Sort methods It is to your advantage to use the type-specific implementation of the List(T) class instead of using the ArrayList class or writing a strongly typed wrapper collection yourself. The reason is your implementation must do what the .NET Framework does for you already, and the common language runtime can share Microsoft intermediate language code and metadata, which your implementation cannot.
Sample code using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> dinosaurs = new List<string>(); Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity); dinosaurs.Add("Tyrannosaurus"); dinosaurs.Add("Amargasaurus"); dinosaurs.Add("Mamenchisaurus"); dinosaurs.Add("Deinonychus");


dinosaurs.Add("Compsognathus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity); Console.WriteLine("Count: {0}", dinosaurs.Count); Console.WriteLine("\nContains(\"Deinonychus\"): {0}", dinosaurs.Contains("Deinonychus")); Console.WriteLine("\nInsert(2, \"Compsognathus\")"); dinosaurs.Insert(2, "Compsognathus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]); Console.WriteLine("\nRemove(\"Compsognathus\")"); dinosaurs.Remove("Compsognathus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } dinosaurs.TrimExcess(); Console.WriteLine("\nTrimExcess()"); Console.WriteLine("Capacity: {0}", dinosaurs.Capacity); Console.WriteLine("Count: {0}", dinosaurs.Count); dinosaurs.Clear(); Console.WriteLine("\nClear()"); Console.WriteLine("Capacity: {0}", dinosaurs.Capacity); Console.WriteLine("Count: {0}", dinosaurs.Count);

} }

/* This code example produces the following output: Capacity: 0 Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus Capacity: 8 Count: 5 Contains("Deinonychus"): True Insert(2, "Compsognathus") Tyrannosaurus Amargasaurus Compsognathus Mamenchisaurus Deinonychus


Compsognathus dinosaurs[3]: Mamenchisaurus Remove("Compsognathus") Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus TrimExcess() Capacity: 5 Count: 5 Clear() Capacity: 5 Count: 0 */

Array / ArrayList / List<T>: An ArrayList or List(T) object is a sophisticated version of an array. The ArrayList class and the List(T) generic class provides some features that are offered in most System.Collections classes but are not in the Array class. For example: Advantage of ArrayList / List<T> over Array: The capacity of an Array is fixed, whereas the capacity of an ArrayList or a List(T) is automatically expanded as required. If the value of the Capacity property is changed, the memory reallocation and copying of elements are automatically done. ArrayList and List(T) provide methods that add, insert, or remove a range of elements. In Array, you can get or set the value of only one element at a time. A synchronized version of ArrayList or List(T) is easy to create using the Synchronized method. The Array class leaves it up to the user to implement synchronization. ArrayList and List(T) provide methods that return read-only and fixed-size wrappers to the collection. Array does not. Advantage of Array over ArrayList / List<T>: You can set the lower bound of an Array, but the lower bound of an ArrayList or a List(T) is always zero. An Array can have multiple dimensions, while an ArrayList or a List(T) always has exactly one dimension. An Array of a specific type (other than Object) has better performance than an ArrayList because the elements of ArrayList are of type Object and, therefore, boxing and unboxing typically occur when storing or retrieving a value type. However, a List(T) can have similar performance to an array of the same type if no reallocations are required; that is, if the initial capacity is a good approximation of the maximum size of the list. Most situations that call for an array can use an ArrayList or a List(T) instead; they are easier to use and, in general, have performance similar to an array of the same type. Array is in the System namespace; ArrayList is in the System.Collections namespace; 38

List(T) is in the System.Collections.Generic namespace.

Queue: FIFO public class Queue : ICollection, IEnumerable, ICloneable This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other. The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The growth factor is determined when the Queue is constructed. o The default growth factor is 2.0. o The capacity of the Queue will always increase by at least a minimum of four, regardless of the growth factor. For example, a Queue with a growth factor of 1.0 will always increase in capacity by four when a greater capacity is required.

Stack: Stack is implemented as a circular buffer.

Dictionary: Dictionary class is used to map a key with a value. 39

They allow us to create a look-up that contains an arbitrary key mapped to an arbitrary value. In order to iterate through a Dictionary collection use DictionaryEntry object Ex: foreach DictionaryEntry de In SampleDictionary { Console.WriteLine(de.Value); to print value; Console.WriteLine(de.Key); to print key; } DictionaryEntry object is the container that contains Key and Value. DictionaryEntry Key + Valu e Hashtable: public class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable Represents a collection of key/value pairs that are organized based on the hash code of the key. Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be a null reference (Nothing in Visual Basic), but a value can be. When an element is added to the Hashtable, the element is placed into a bucket based on the hash code of the key. Subsequent lookups of the key use the hash code of the key to search in only one particular bucket, thus substantially reducing the number of key comparisons required to find an element. Sorted List:

public class SortedList : IDictionary, ICollection, IEnumerable, ICloneable Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index. A SortedList element can be accessed by its key, like an element in any IDictionary implementation, or by its index, like an element in any IList implementation. A SortedList object internally maintains two arrays to store the elements of the list; that is, one array for the keys and another array for the associated values. Each element is a key/value pair that can be accessed as a DictionaryEntry object. A key cannot be nullNothingnullptra null reference (Nothing in Visual Basic), but a value can be. SortedList does not allow duplicate keys.

Collection String:



It is a dynamically re-sizeable collection similar to the ArrayList, which stores only Strings. StringDictionary: It is strongly typed version of the Dictionary collection; i.e., we can use this like Hashtable but both the key and value should be string type.



Advantage of ADO.Net: ADO.NET Does Not Depend On Continuously Live Connections Database Interactions are performed using Data Commands 42

Data Can Be Cached in Datasets Datasets Are Independent of Data Sources Data is Persisted as XML Schemas Define Data Structures

Comparison of ADO and ADO.Net:

In ADO, the in-memory representation of data is the recordset In ADO.NET, the in-memory representation of data is the dataset
A recordset looks like a single table A dataset is a collection of one or more table

In ADO you scan sequentially through the rows of the recordset using the
ADO MoveNext method

In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index.

ADO is designed primarily for connected access.

ADO.NET opens connection only long enough to perform a database operation, such as a Select or Update Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.

Data Is Persisted as XML Data needs to be moved from the data store to the dataset and from there to various components. In ADO.NET the format for transferring data is XML. Similarly, if data needs to be persisted (for example, into a file), it is stored as XML. If you have an XML file, you can use it like any data source and create a dataset out of it. In fact, in ADO.NET, XML is a fundamental format for data. The ADO.NET data APIs automatically create XML files or streams out of information in the dataset and send them to another component. The second component can invoke similar APIs to read the XML back into a dataset. (The data is not stored in the dataset as XML for example, you cannot parse data in a dataset using an XML parser but instead in a more efficient format.) Basing data protocols around XML offers a number of advantages:
XML is an industry-standard format. This means that your application's data

components can exchange data with any other component in any other application, as long as that component understands XML. Many applications are being written to understand XML, which provides an unprecedented level of exchange between disparate applications.
XML is text-based. The XML representation of data uses no binary information,

which allows it to be sent via any protocol, such as HTTP. Most firewalls block binary information, but by formatting information in XML, components can still easily exchange the information. 43

Data Provider:

Data Provider provides access to data source (SQL SERVER, ACCESS, and ORACLE). In short it provides object to achieve functionalities like opening and closing connection, retrieve data and update data.

Connection object: A connection object is used to connect to a specific data source by supplying necessary authentication information in a connection string.

The Connection object you use depends on the type of data source. The connection class implements IDbConnection interface Each .NET Framework data provider included with the .NET Framework has a DbConnection object To connect to Microsoft SQL Server 7.0 or later, use the SqlConnection object of the .NET Framework Data Provider for SQL Server. To connect to an OLE DB data source, or to Microsoft SQL Server 6.x or earlier, use the OleDbConnection object of the .NET Framework Data Provider for OLE DB. To connect to an ODBC data source, use the OdbcConnection object of the .NET Framework Data Provider for ODBC. To connect to an Oracle data source, use the OracleConnection object of the .NET Framework Data Provider for Oracle. To obtain connection string from web.config file
// Retrieve the partial connection string named databaseConnection // from the application's app.config or web.config file. ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["partialConnectString"];

You can also use the SqlConnectionStringBuilder class to create syntactically valid connection strings at run time.
private static void BuildConnectionString(string dataSource, string userName, string userPassword) { // Retrieve the partial connection string named databaseConnection // from the application's app.config or web.config file. ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["partialConnectString"]; if (null != settings) {


// Retrieve the partial connection string. string connectString = settings.ConnectionString; Console.WriteLine("Original: {0}", connectString); // Create a new SqlConnectionStringBuilder based on the // partial connection string retrieved from the config file. SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString); // Supply the additional values. builder.DataSource = dataSource; builder.UserID = userName; builder.Password = userPassword; Console.WriteLine("Modified: {0}", builder.ConnectionString);

} }

Connection string syntax Standard Security: Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername; Password=myPassword; Use serverName\instanceName as Data Source to connect to a specific SQL Server instance. When using SQL Server 2008 Express don't miss the server name syntax Servername\SQLEXPRESS where you substitute. The above format is also applicable when you want to use named instance of a server. Servername name of the computer where the SQL Server Express installation resides. Keywords with Connection-string:
Data Source -orServer -orAddress -orAddr -orNetwork Address N/A The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name: server=tcp:servername, portnumber When specifying a local instance, always use (local). To force a protocol, add one of the following prefixes: np:(local), tcp:(local), lpc:(local) Data Source must use the TCP format or the Named Pipes format. TCP format is as follows: tcp:<host name>\<instance name> tcp:<host name>,<TCP/IP port number> The TCP format must start with the prefix "tcp:" and is followed by the database instance, as specified by a host name and an instance name. The host name MUST be specified in one of the following ways: NetBIOSName IPv4Address IPv6Address


The instance name is used to resolve to a particular TCP/IP port number on which a database instance is hosted. Alternatively, specifying a TCP/IP port number directly is also allowed. If both instance name and port number are not present, the default database instance is used. The Named Pipes format is as follows: np:\\<host name>\pipe\<pipe name> The Named Pipes format MUST start with the prefix "np:" and is followed by a named pipe name. The host name MUST be specified in one of the following ways: NetBIOSName IPv4Address IPv6Address The pipe name is used to identify the database instance to which the .NET Framework application will be connected. If the value of the Network key is specified, the prefixes "tcp:" and "np:" should not be specified. Note ADO.NET 2.0 does not support asynchronous commands over shared memory for SQL Server 2000 or earlier. However, you can force the use of TCP instead of shared memory, either by prefixing tcp: to the server name in the connection string, or by using localhost. Encrypt 'false' When true, SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed. Recognized values are true, false, yes, and no. N/A The name of the database. The database name can be 128 characters or less.

Initial Catalog -orDatabase Integrated Security -orTrusted_Connection

'false' When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication. Recognized values are true, false, yes, no, and sspi (strongly recommended), which is equivalent to true. If User ID and Password are specified and Integrated Security is set to true, the User ID and Password will be ignored and Integrated Security will be used.

Max Pool Size


The maximum number of connections that are allowed in the pool. Valid values are greater than or equal to 1. Values that are less than Min Pool Size generate an error.

Min Pool Size

The minimum number of connections that are allowed in the pool. Valid values are greater than or equal to 0. Zero (0) in this field means no minimum connections are initially opened. Values that are greater than Max Pool Size generate an error.


MultipleActiveResult Sets

'false' When true, an application can maintain multiple active result sets (MARS). When false, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection. Recognized values are true and false. The keyword is not supported by .NET Framework version 1.0 or 1.1.

Packet Size

8192 Size in bytes of the network packets used to communicate with an instance of SQL Server. The packet size can be greater than or equal to 512 and less than or equal to 32768.

Password -orPWD

The password for the SQL Server account logging on. Not recommended. To maintain a high level of security, we strongly recommend that you use the Integrated Security or Trusted_Connection keyword instead. The password must be 128 characters or less.

Persist Security Info -orPersistSecurityInfo

When set to false or no (strongly recommended), security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password. Recognized values are true, false, yes, and no.

The default setting for PersistSecurity Info keyword is false. Setting it to true or yes allows security-sensitive information, including the user ID and password, to be obtained from the connection after the connection has been opened. Keep PersistSecurity Info set to false to ensure that an untrusted source does not have access to sensitive connection string information.

Connection Pool: Connection pooling is the process of reusing active database connections instead of creating a new connection with every request ADO.NET with IIS uses a technique called connection pooling. What it does is, on first request to database, it serves the database call. Once it is done and when the client application requests for closing the connection, ADO.NET does not destroy the complete connection, rather it creates a connection pool and puts the released connection object in the pool and holds the reference to it. And next time when the request to execute any query/stored proc comes up, it bypasses the hefty process of establishing the connection and just picks up the connection from the connection pool and uses that for this database call. This way, it can return the results comparatively faster. Pool creation and assignment


When a connection is first opened, a connection pool is created based on an exact matching algorithm that associates the pool with the connection string in the connection. Each connection pool is associated with a distinct connection string. When a new connection is opened, if the connection string is not an exact match to an existing pool, a new pool is created. Connections are pooled per process, per application domain, per connection string per Windows identity (when integrated security is used). Connection strings must also be an exact match; keywords supplied in a different order for the same connection will be pooled separately. Name Defau Description lt When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified byConnection Lifetime. A value of zero (0) causes pooledconnections to have the maximum connection timeout. Maximum Time (in secs) to wait for a free connection from the pool When true, the pooler automatically enlists the connection in the creation thread's current transaction context. Recognized values aretrue, false, yes, and no. Set Enlist = "false" to ensure thatconnection is not context specific. The maximum number of connections allowed in the pool. Most Web sites do not use more than 40 connections under the heaviest load but it depends on how long your database operations take to complete. The minimum number of connections allowed in the pool. However, you may chose to set this to a small number such as 5 if your application needs consistent response times even after it was idle for hours. In this case the first user requests won't have to wait for those database connections to establish When true, the SQLConnection object is drawn from the appropriate pool, or if it is required, is created and added to the appropriate pool. Recognized values are true, false, yes, and no. Controls the number of connections that are established when all theconnections are used. Controls the number of connections that are closed when an excessive amount of established connections are unused.

ConnectionLif 0 etime

ConnectionTi meout Enlist



Max PoolSize


Min PoolSize



Incr PoolSize

Decr PoolSize 1

Integrated Security and ASP.NET SQL Server integrated security (also known as trusted connections) helps to provide protection when connecting to SQL Server as it does not expose a user ID and 48

password in the connection string and is the recommended method for authenticating a connection. Integrated security uses the current security identity, or token, of the executing process. For desktop applications, this is typically the identity of the currently logged-on user. Closing of Connection object:

In order to dispose connection object Use Connection Obj. Close() method in the finally block. Use Using clause

string source = "server=(local); integrated security=SSPI; database=Northwind"; using ( SqlConnection conn = new SqlConnection ( source ) ) { // Open the connection conn.Open ( ) ; // Do something useful }

The using clause ensures that the connection is closed, how so ever the block is exited. However it is best to use both the above methods to close the connection object; the sample code is given below
try { using (SqlConnection conn = new SqlConnection ( source )) { // Open the connection conn.Open ( ) ; // Do something useful // Close it myself conn.Close ( ) ;

} } catch (SqlException e) { // Log the exception }

The machine.config file for .NET 2.0, contains the DbProviderFactories section - this maps the alias names (such as System.Data.SqlClient) to the factory object for that type of database. The DbProviderFactory class just looks up the factory class from the machine configuration settings, and uses that concrete factory class to instantiate the connection object. In the case of the SqlClientFactory class, all this does is construct an instance of SqlConnection and return this to the caller. Transaction:

Usually when more than one update needs to be done, it should be done within the scope of the Transaction. A transaction is initiated by calling BeginTransaction() method on the Connection object. 49

This method returns an object that implements IDbTransaction interface.

string source = "server=(local);integrated security=SSPI;" + "database=Northwind"; SqlConnection conn = new SqlConnection(source); conn.Open(); SqlTransaction tx = conn.BeginTransaction(); // Execute some commands, then commit the transaction tx.Commit(); conn.Close();

Command: A command is, in its simplest form, is the set of database commands that is to be issued to the database. A data command contains a reference to an SQL statement or stored procedure that you can execute directly. A data command is an instance of the OleDbCommand, SqlCommand, OdbcCommand, or OracleCommand class; as with other such classes, OleDbCommand class can be used with any OLE DB provider, SqlCommand class is optimized for use with SQL Server 7.0 or later, OdbcCommand class is for use with ODBC data sources, and OracleCommand class is for use with Oracle databases. A command could be String of text containing SQL statements Stored procedure, or Name of a table that will return all columns and all rows from that table (in other words, a SELECT *-style clause). CommandType: CommandTy Example pe Text (default) String select = SELECT ContactName FROM Customers; SqlCommand cmd = new SqlCommand(select , conn); StoredProced SqlCommand cmd = new ure SqlCommand(CustOrderHist, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue(@CustomerID, QUICK); TableDirect OleDbCommand cmd = new OleDbCommand(Categories, conn); 50

CommandTy Example pe cmd.CommandType = CommandType.TableDirect; TableDirect is used only with OleDb type only Command Execution: Item BeginExecuteNonQ uery Description Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, generally executing commands such as INSERT, DELETE, UPDATE, and SET statements. Each call to BeginExecuteNonQuery must be paired with a call to EndExecuteNonQuery which finishes the operation, typically on a separate thread.

BeginExecuteReade Initiates the asynchronous execution of the Transact-SQL r statement or stored procedure that is described by this SqlCommand and retrieves one or more results sets from the server. Each call to BeginExecuteReader must be paired with a call to EndExecuteReader which finishes the operation, typically on a separate thread. BeginExecuteXmlR eader Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand. Each call to BeginExecuteXmlReader must be paired with a call to EndExecuteXmlReader, which finishes the operation, typically on a separate thread, and returns an XmlReader object. Executes commands that return rows. For increased performance, ExecuteReader invokes commands using the Transact-SQL sp_executesql system stored procedure. Therefore, ExecuteReader might not have the effect that you want if used to execute commands such as Transact-SQL SET statements. Executes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements. Retrieves a single value (for example, an aggregate value) from a database. The return type is Object, which can be casted to the required data type. Sends the CommandText to the Connection and builds an XmlReader object.





Under some circumstances, you cannot use a dataset. For example, if you want to create database elements such as tables, you must use data commands. 51

Return Value of DDL / DML operations using command: The return value differs according to whether you are updating records or issuing a DDL command:
DML: If you are creating or modifying database structures, o o

Return value when operation was successful -1 Return value when operation was not successful 0

DDL: If you are updating records, o o

Return value when operation was successful number of records affected by operation Return value when operation was not successful 0

Obtaining data as XML from SQL server:

Microsoft SQL Server 2000 introduces support for XML functionality when retrieving data

ExecuteXmlReader returns a System.Xml.XmlReader object populated with the results of the SQL statement specified for a SqlCommand
SqlCommand custCMD = new SqlCommand("SELECT * FROM Customers FOR XML AUTO, ELEMENTS", nwindConn); System.Xml.XmlReader myXR = custCMD.ExecuteXmlReader();

Applications of Data Command object:

Execute Select commands that return a result you can read directly, rather than

loading it into the dataset. To read the results, you use a data reader (OleDbDataReader,SqlDataReader, OdbcDataReader, or OracleDataReader object), which works like a read-only, forward only cursor and that you can bind controls to. This is a useful strategy for reducing memory usage and loading read-only data very quickly. Execute database definition (DDL) commands to create, edit, and remove tables, stored procedures, and other database structures. (You must have permissions to perform these actions, of course.) Execute commands to get database catalog information. Execute dynamic SQL commands to update, insert, or delete records rather than updating dataset tables and then copying changes to the database. Execute commands that return a scalar value (that is, a single value), such as the results of a credit-card authentication lookup or a calculated value. Execute commands that return data from a SQL Server database (version 7.0 or later) in XML format. A typical use is to execute a query and get back data in XML format, apply an XSLT transform to it (to convert the data to HTML), and then send the results to a browser.

Multiple Resultset: A typical use of data commands is to return a single result set. However, data commands can execute procedures that return multiple results sets. Returning multiple result sets allows you to optimize your use of a single open connection. For Oracle, the .NET Framework Data Provider for Oracle does not support batched SQL statements. However, it does allow you to use multiple REF CURSOR output parameters to fill a dataset, each in its own data table. You 52

must define the parameters, mark them as output parameters, and indicate that they are REF CURSOR data types. Note that you will be unable to use the Update method when the OracleDataAdapter object is filled from REF CURSOR parameters to a stored procedure, because Oracle does not provide the information necessary to determine what the table name and column names are when the SQL statement is executed. Data Adapter: Data adapters are set of objects that are used to communicate between dataset and the datasource. Automatically Generated Commands: For cases where the SelectCommand is dynamically specified at runtime, such as through a query tool that takes a textual command from the user, you may not be able to specify the appropriate InsertCommand, UpdateCommand, or DeleteCommand at design time. If your DataTable maps to or is generated from a single database table, you can take advantage of the CommandBuilder object to automatically generate the DeleteCommand, InsertCommand, and UpdateCommand of the DataAdapter. As a minimum requirement, you must set the SelectCommand property in order for automatic command generation to work. The table schema retrieved by the SelectCommand determines the syntax of the automatically generated INSERT, UPDATE, and DELETE statements. The CommandBuilder must execute the SelectCommand in order to return the metadata necessary to construct the insert, update, and delete commands. As a result, an extra trip to the data source is necessary which can hinder performance. To achieve optimal performance, specify your commands explicitly rather than using the CommandBuilder. The SelectCommand must also return at least one primary key or unique column. If none are present, an InvalidOperation exception is generated, and the commands are not generated. When associated with a DataAdapter, the CommandBuilder automatically generates the InsertCommand, UpdateCommand, and DeleteCommand properties of the DataAdapter if they are null references. If a Command already exists for a property, the existing Command is used. Database views that are created by joining two or more tables together are not considered a single database table. In this instance you will not be able to use the CommandBuilder to automatically generate commands and will need to specify your commands explicitly. For information about explicitly setting commands to resolve updates to a DataSet back to the data source, see Updating the Database with a DataAdapter and the DataSet. Rules for automatically generated commands:
Command Rule

InsertComman Inserts a row at the data source for all rows in the table with d a RowState of DataRowState.Added. Inserts values for all columns that are updateable (but not columns such as identities, expressions, or timestamps). UpdateComma Updates rows at the data source for all rows in the table with nd a RowState of DataRowState.Modified. Updates the values of all columns except for columns that are not updateable, such as identities or expressions. Updates all rows where


the values at the data source match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. DeleteComma Deletes rows at the data source for all rows in the table with nd a RowState of DataRowState.Deleted. Deletes all rows where the column values match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. For more information, see the section in this topic on the "Optimistic Concurrency Model for Updates and Deletes".

Dim Dim Dim Dim Dim Dim

dSet As DataSet dRow As DataRow dTable As DataTable sqlCmd As SqlCommand sqlConn As SqlConnection sqlDapter As SqlDataAdapter

sqlConn = New SqlConnection("..........") sqlDapter = New SqlDataAdapter sqlCmd = New SqlCommand("SELECT * FROM MyTable", sqlConn) sqlDapter.SelectCommand = sqlCmd dSet = New DataSet sqlDapter.Fill(dSet, "MyTable") dTable = New DataTable dTable = dSet.Tables("MyTable") dRow = dTable.NewRow dRow(0) = 1 dRow(1) = "peter" dTable.Rows.Add(dRow) sqlCmd = New SqlCommand("INSERT INTO MyTable (Col1, Col2) VALUES (@Val1, @Val2)", sqlConn) With sqlCmd .Parameters.Add("@Val1", SqlDbType.Int).Value = 1 .Parameters.Add("@Val2", SqlDbType.VarChar, 50).Value = "peter" End With sqlDapter.InsertCommand = sqlCmd sqlDapter.Update(dSet.Tables("MyTable"))

Data Reader: ADO.Net uses Data reader to retrieve Read-only and forward-only stream of data from the database. Results are returned as the query executes, and are stored in the network buffer on the client until you request them using the Read method of the DataReader Using the DataReader can increase application performance both by retrieving data as soon as it is available, rather than waiting for the entire results of the query to be returned, and (by default) storing only one row at a time in memory, reducing system overhead. The DataReader provides an unbuffered stream of data 54

The DataReader is a good choice when retrieving large amounts of data because the data is not cached in memory. Multiple Result set: If Multiple result set are retrieved, then NextResult method can be used to iterate through the result set in order.
SqlCommand myCMD = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;" + "SELECT EmployeeID, LastName FROM Employees", nwindConn); nwindConn.Open(); SqlDataReader myReader = myCMD.ExecuteReader(); do { Console.WriteLine("\t{0}\t{1}", myReader.GetName(0), myReader.GetName(1)); while (myReader.Read()) Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1)); } while (myReader.NextResult()); myReader.Close(); nwindConn.Close();

Dataset: Dataset namespace:

The DataRow class includes the RowState property, whose values indicate whether and how the row has been changed since the data table was first loaded from the database. Possible values for the RowState property include Deleted, Modified, New, and Unchanged
Datasets, Schemas, and XML

An ADO.NET dataset is one view a relational view of data that can be represented in XML The structure of a dataset its tables, columns, relationships, and constraints can be defined in an XML Schema You can read an XML document or stream into a dataset using the dataset's ReadXML method and write a dataset out as XML using the dataset's WriteXML method. Because XML is a standard interchange format for data between different applications, this means that you can load a dataset with XML-formatted information sent by other applications. Similarly, a dataset can write out its data as an XML stream or document, to be shared with other applications or simply stored in a standard format. 55

Typed versus Un-typed dataset: Typed dataset:

Typed dataset is that dataset, which initially derives from the base Dataset class and then uses the information in a XML schema file (.xsd file) to generate a new class. Un-Typed dataset: An un-typed dataset, in contrast, has no corresponding built-in schema. As in a typed dataset, an un-typed dataset contains tables, columns, and so on but those are exposed only as collections. (However, after manually creating the tables and other data elements in an untyped dataset, you can export the dataset's structure as a schema using the dataset's WriteXmlSchema method.) Data Access using Type dataset: Typed dataset: string s; s = dsCustomersOrders1.Customers[0].CustomerID; Un-Typed dataset: string s; string s = (string) dsCustomersOrders1.Tables["Customers"].Rows[0] ["CustomerID"]; Access to tables and columns in a typed dataset is also slightly faster at run time because access is determined at compile time, not through collections at run time. It would be reasonable to ask, however, whether these things are any faster or slower than regularDataSets. You may already know that throwing exceptions incurs a slight overhead from the runtime, as does typecasting. All of the properties and functions in a strongly typed DataSet are wrapped in exception-handling calls, and a great many are wrapped in typecasting code. This leads some people to believe that they are slightly less efficient than standardDataSets. However, in any production application, you'll be wrapping your DataSet in exception-handling and typecasting code anyway, so the fact that the typed DataSet does this for you should be considered an advantage and not a performance drain. Populating a dataset: Call the Fill method of a data adapter. Manually populate tables in the dataset by creating DataRow objects and adding them to the table's Rows collection. Read an XML document or stream into the dataset. Merge (copy) the contents of another dataset. DataColumn: The ExtendedProperties property lets you store custom information with the object. For example, you may store a time when the data should be refreshed. Extended properties must be of type String. Properties that are not of type String are not persisted when the DataColumn is written as XML. 56

private void SetProperty(DataColumn column) { column.ExtendedProperties.Add("TimeStamp", DateTime.Now); } private void GetProperty(DataColumn column) { Console.WriteLine(column.ExtendedProperties["TimeStamp"].ToString()); }


One of the most appealing aspects of DataRow is that it is versioned. This permits you to receive various values for a given column in a particular row. The versions are described in the following table. The RowState property is set to keep track of all the changes made to the DataTable, such as adding new rows, deleting existing rows, and changing columns within the table. When the data is reconciled with the database, the row state flag is used to determine what SQL operations should occur.

DataRow Version Value Current


The value existing at present within the column. If no edit has occurred, this will be the same as the original value. If an edit (or edits) has occurred, the value will be the last valid value entered. The default value (in other words, any default set up for the column). The value of the column when originally selected from the database. If the DataRows AcceptChanges method is called, this value will update to the Current value. When changes are in progress for a row, it is possible to retrieve this modified value. If you call BeginEdit() on the row and make changes, each column will have a proposed value until either EndEdit() or CancelEdit() is called.

Default Original


Schema Generation

You can create the schema for a DataTable in three ways:

Let the runtime do it for you. Write code to create the table(s). Use the XML schema generator.
DataSet ds = new DataSet("Relationships"); ds.Tables.Add(CreateBuildingTable()); ds.Tables.Add(CreateRoomTable()); ds.Relations.Add("Rooms", ds.Tables["Building"].Columns["BuildingID"],

Data Relationship:



Obtain the child rows:

foreach(DataRow theBuilding in ds.Tables["Building"].Rows) { DataRow[] children = theBuilding.GetChildRows("Rooms"); int roomCount = children.Length; Console.WriteLine("Building {0} contains {1} room{2}", theBuilding["Name"], roomCount, roomCount > 1 ? "s" : ""); // Loop through the rooms foreach(DataRow theRoom in children) Console.WriteLine("Room: {0}", theRoom["Name"]); }

To obtain the parent row

foreach(DataRow theRoom in ds.Tables["Room"].Rows) { DataRow[] parents = theRoom.GetParentRows("Rooms"); foreach(DataRow theBuilding in parents) Console.WriteLine("Room {0} is contained in building {1}", theRoom["Name"], theBuilding["Name"]); }


Constraints are rules that are applied when rows are inserted, updated, or deleted in a table. You can define two types of constraints:
A unique constraint that checks that the new values in a column are unique

in the table.

You can specify a unique constraint for other columns by setting their Unique property to true

A foreign-key constraint that defines rules for how related child records

should be updated when a record in a master table is updated or deleted. Constraint Description

ForeignKeyCons Enforces a link between two DataTables within traint a DataSet.




UniqueConstrai Ensures that entries in a given column are unique. nt

Setting a primary key:

public static void ManufacturePrimaryKey(DataTable dt) { DataColumn[] pk = new DataColumn[1]; pk[0] = dt.Columns["ProductID"]; dt.PrimaryKey = pk; }

When a primary key is created for the datatable, the run time also generates a unique constraint for that column. The primary key is nothing but a unique constraint over one or more columns. To check the constraints applicable on a datatable we can use the ConstraintCollection. Because a primary key can contain several columns, it is typed as an array of DataColumns. A tables primary key can be set to those columns simply by assigning an array of columns to the property.

Setting a foreign key:

DataColumn parent = ds.Tables["Categories"].Columns["CategoryID"]; DataColumn child = ds.Tables["Products"].Columns["CategoryID"]; ForeignKeyConstraint fk = new ForeignKeyConstraint("FK_Product_CategoryID", parent, child); fk.UpdateRule = Rule.Cascade; fk.DeleteRule = Rule.SetNull; ds.Tables["Products"].Constraints.Add(fk); There are 4 different types of foreign key constraints Cascade - If the parent key has been updated, copy the new key value to all child records. If the parent record has been deleted, delete the child records also. This is the default option. None - No action whatsoever. This option leaves orphaned rows within the child data table.


SetDefault - Each child record affected has the foreign key column(s) set to its default value, if one has been defined. SetNull - All child rows have the key column(s) set to DBNull. (Following the naming convention that Microsoft uses, this should really beSetDBNull). The constraints are enforced only when the EnforceConstraints property of the Dataset class is set to true.

Database: SQL / Oracle:

Database object: A database object is a defined object, which is used to store or reference data. Schema: It is collection of database objects associated with one particular database username. The username is called schema owner. A schema is owned by the database user. It has the same name as the Database user. Primary Key Constraints Primary key is the term used to identify one or more columns in a table that make a row of data unique Foreign Key Constraints A foreign key is a column in a child table that references a primary key in the parent table. A foreign key constraint is the main mechanism used to enforce referential integrity between tables in a relational database. A column defined as a foreign key is used to reference a column defined as a primary key in another table 60

Authentication & Authorization:

Authentication: o Authentication is the means, by which you obtain the Identity of the User by validating their credentials against a known Authority, ie: Active Directory, Database Store, Microsoft Passport Account etc

Authorization: o o It is the process of determining if an authenticated user has access to the Resource he had requested from the IIS website. The process of identifying the rights for a resource is called Authorization

The following shows the sequence of authentication and authorization actions performed by IIS and ASP.NET on an incoming request. 1. The incoming request is first checked by IIS. If the IP address from where the request is sought is not allowed access to the domain, IIS denies the request. 2. IIS allows anonymous access by default and hence requests are automatically authenticated. However, this can be overridden for each application within IIS. Next in the sequence IIS performs this authentication, if it has been configured to do so. 3. The authenticated user request is passed to ASP.NET. 4. ASP.NET checks whether Impersonation is enabled or not. By default impersonation is not enabled in ASP .NET. Generally, some applications require impersonation for ASP compatibility and Windows server authentication. (By default, the ASP.NET engine operates under the ASPNET user account. 61

Impersonation is a means by which you can have the ASP.NET engine operates under the authenticated user's user account. )
o o

If impersonation is enabled, ASP.NET executes with the identity of the entity on behalf of which it is performing executing the task. If impersonation is not enabled, the application runs with the privileges of the ASPNET user account.

5. Finally, the identity that has been authenticated and checked for in the previous steps is used to request resources from the OS. ASP.NET uses two forms of authorization:
o o

FileAuthorization - relies on NTFS file permissions for granting access. UrlAuthorization - in the Web.config file you can specify the authorization rules for various directories or files using the <authorization> element.

6. If access is granted (successful authorization), ASP .NET returns the user's request through IIS. To impersonate: use the below line in web.config <identity impersonate="true" userName="accountname" password="password" />


Detecting Authentication & Authorization To get Authentication details: Identity Object To get Authorization details: Principal Object
Response.Write(User.Identity.Name +"<br>"); Response.Write(User.Identity.AuthenticationType + "<br>"); Response.Write(User.Identity.IsAuthenticated + "<br>"); Response.Write(User.IsInRole("Administrators") + "<br>");

Authentication: ASP.NET provides three ways to authenticate a user:

Windows authentication, Forms authentication, and Passport authentication

<configuration> <system.web> <authentication mode="[Windows/Forms/Passport/None]"> </authentication> </system.web> </configuration>


Windows Authentication: ASP.NET will use local windows users and groups viz., windows account to authenticate and authorize resources. It is the default Authentication provider for ASP.Net. It is dependent on IIS

Windows authentication is generally used if the users accessing the application belong to same organization. This authentication method uses Windows accounts for validating users' credentials. This type of authentication is very good for intranet Web sites where we know our users. o There are 4 kinds of windows authentication Anonymous IIS doesn't perform any authentication check. IIS allows any user to access the ASP .NET application. o Basic Authentication: The Windows user name and password has to be provided to connect and this information is sent over the network in plain text, and, hence, this is an insecure method of authentication. When basic authentication is selected the userid and password are passed by using Base64 encoded format o Digest Authentication: It is the same as basic authentication except that the password is hashed before it is sent across the network. It sends data as MD5 hash or message digest. Digest authentication is its not supported on some browsers o Integrated Windows Authentication: In this kind of authentication technique, passwords are not sent across the network. The application here uses either the kerberos or challenge/response protocols to authenticate users. Forms Authentication: It provides the user an HTML form based page wherein the user provides the user name and password. This is a cookie based Authentication where the user name and password are stored in cookies or they are sent through URL for every request. It is called Forms Authentication since the user enters his credentials via a form Forms authentication is handled by a special class called FormsAuthentication class You can optionally issue an authentication cookie to prevent authenticated users from having to log in time and time again. 64

Enable Forms Authentication:

' web.config file <configuration> <system.web> <authentication mode= "Forms"> <forms name=".ASPXAUTH" loginUrl="MyLoginForm.aspx" /> </authentication> </system.web> </configuration>

You can also optionally specify the name of the Authentication cookie used (if no name is specified the default is .ASPXAUTH

Authentication Process

Once the Forms Authentication Provider is configured, all unauthenticated requests for protected resources will be redirected to the loginUrl using clientside redirection. Write custom code that authenticates the users credentials stored in either database / xml / hard coded in the page. Once validation and authentication have taken place the user can simply be returned to the resource that initially requested the authentication by calling the RedirectFromLoginPage() static method of the FormsAuthentication Provider which redirects, based on the contents of the ReturnURL key in the query string, or redirects to Default.aspx if the return key does not exist. Method: FormsAuthentication.RedirectFromLoginPage (txtUserName.Text, False) o o The first parameter uniquely identifies the user so that, on other pages, we can easily determine who this visitor is; The second parameter is a Boolean value that indicates if we want to keep the user's authentication cookie across multiple site visits.

By default the RedirectFromLoginPage method issues a temporary cookie that expires when the browser is closed. This cookie can be made to persist for 50 years by passing True as the second argument of this method. If no cookie is present the redirect takes place and a ReturnURL is appended to the querystring. o For example, if we setup ourloginUrl to /MyLoginForm.aspx and then attempted to access a protected resource at /SomeProtectedResource.aspx, the Forms Authentication setup would automatically redirect us to the following URL: /MyLoginForm.aspx?ReturnURL=/SomeProtectedResource.aspx

Methods of Authenticating

You could store the user credentials

In a database, 65

In an XML file, or Have their information hard coded in the login page

Storing the credentials in web.config:

<configuration> <system.web> <authentication mode="Forms"> <forms loginUrl="MyLoginPage.aspx"> <credentials passwordFormat="Clear"> <user name="Darren" password="foobar" /> </credentials> </forms> </authentication> <authorization> </system.web> </configuration> If FormsAuthentication.Authenticate (txtUserName.Text, txtPassword.Text) Then FormsAuthentication.RedirectFromLoginPage (UserName.Text, False) Else Invalid credentials supplied, display message lblMessage.Text = "Invalid login credentials" End If

Passport Authentication: It is a centralized authentication method Passport authentication is based on the passport website provided by the Microsoft. So when user logins with credentials it will be redirected to the passport website (i.e. hotmail, devhood, windows live etc) where authentication will happen. If Authentication is successful it will return a token to your website. When using the Passport Authentication provider you need to have the Passport SDK installed and also be a registered member to use the service.


ASP.NET State Management Overview

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server. Different State Management options:
View state Control state Hidden fields Cookies A cookie is a small file which is stored in the visitor's hard disk drive. This is helpful for storing small and trivial information. A cookie can have a maximum size of 4KB. The web server creates a cookie, attaches an additional HTTP header to the response, and sends it to the browser. The browser will then create this cookie in a visitor's computer and includes this cookie for all further requests made to the same domain. Servers can read the cookie value from the request and retain the state. The server adds the following to the HTTP header for creating a cookie
Set-Cookie: key=value

The browser reads the above value and creates cookies at the user's end. It adds the cookie value to the request like
Cookie: key=value

When no expiry time is set, the cookie will be cleared once the browser is closed.

// this cookie expires after one day from the date it is set // browser will take care about removing the cookies after the expiry time Response.Cookies["id"].Value = "10"; Response.Cookies["id"].Expires = DateTime.Now.AddDays(1); // for safety, always check for NULL as cookie may not exist if (Request.Cookies["id"] != null) { string userId = Request.Cookies["id"].Value; Response.Write("User Id value" + userId); }

Multi-valued cookie: 67

HttpCookie cookie = new HttpCookie("user"); cookie["name"] = "Foo"; cookie["age"] = "22"; cookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(cookie);

Query strings

An URL can have a maximum of 2083 characters, this is dependent on browsers. A querystring cannot contain non-ASCII characters. If we need to use non-Ascii characters in the querystring then use Server.UrlEncode and Server.UrlDecode methods. Use the encryption methods from the System.security.Cryptography namespace to encrypt the url.
Application state

A global storage mechanism that is accessible from all pages in the Web application Application state is stored in the Application key/value dictionary. Application state is a great place to store information that is not userspecific.
Session state

ASP.NET maintains a unique id which is called as "session id" for each session Session id will be sent to the client as a cookie and the browser resends this upon each request. ASP.NET uses this session id to identify the session object. ASP.NET sends session id in a cookie named ASP.NET_SessionId.
ASP.NET allows three types of session storage which are described below InProc: In Process memory StateServer: It runs as a separate windows service and keeps the session data out of ASP.NET process memory area. Sql Server: in a sql server

Profile Properties Control state:

Control state survives even if the developer using the custom control disables view state. The advantage is pretty obvious; in prior versions of Visual Studio, the consumer of a custom control could disable view state; if the control relied on view state to maintain state information, the control would cease to function or at least misbehave. Creating control state removed the ability of a control consumer to disable view state based state management within the control; naturally, the control designer may still opt to not use either view state or control state based state management. 68

What Where? ?

Who can see

Life span

Issues limited data size (typically 4096 bytes), cookie limit (typically 20 per site)user can disable

New in


Cookies Request.Coo User's current browser String curren kies browser session or set s t user Response.Co or disk expire date okies one page Hidden HTML String curren browser postback (one fields s t user round trip) web all Objec until server is server sessio ts restarted RAM (1) ns

ancien t history !

ancien limited to text t Easy to and visible as history hack! Page Source text ! limited by RAM Classic ASP



end of user's session web Objec curren (Session.Abando server limited by RAM ts t user n or timeout RAM (1) [default 20 minutes])

Classic ASP


hidden one page Objec curren INPUT in postback (one ts t user page round trip)

Can be disabled by bandwidth and the slower page load ASP.Ne developer <i>and</i> post t 1.0 (per page, times web.config or code) Cannot be disabled by Not as simple to ASP.Ne the use as ViewState t 2.0 developer using the control You must always ASP.Ne Can be used check to see if the t 1.0 as an

in one page Objec curren ControlState ViewStat postback (one ts t user e round trip)

Cache (2)

web server

Objec all Until: ts sessio - Expires




- a dependency changes - RAM is needed

object still exists as cached items are both automatically deleted and are deleted when RAM runs low.

Application object that can expire

(1) State can be stored in local server RAM (InProc), another server's RAM (StateServer), SQL Server (SQLServer) or a custom destination. For any option other than InProc all objects must be serializable. (2) Cache is not usually mentioned in lists of state options, but is nearly identical to Application with the addition of expiration.