NET Framework
The .NET Framework is a platform for building, deploying, and running Web Services and
applications. It consist of components such as common language runtime (CLR) and the .NET
Framework class library, which includes classes, interfaces, and value types that support wide
range of technologies.
The .NET Framework is a class of reusable libraries (collection of classes) given by Microsoft to
be used in other , also .NET Framework provides an execution environment, simplified
development and deployment, and integration with a variety of programming languages,
including Visual Basic and Visual C#.
.Net Framework Architecture - The .NET Framework consists of three main parts:
1. Common Language Runtime - The common language runtime is the foundation of the .NET
Framework. Think of the runtime as an agent that manages code at execution time, providing
core services such as memory management, thread management, and remoting, while also
enforcing strict type safety and other forms of code accuracy that promote security and
robustness. In fact, the concept of code management is a fundamental principle of the runtime.
Code that targets the runtime is known as managed code, while code that doesn't target the
runtime is known as unmanaged code.
2. Unified class libraries - The .NET Framework includes a set of standard class libraries. A class
library is a collection of methods and functions that can be used for the core purpose.
3. Active Server Pages called ASP.NET - This is used for developing web-based applications,
which are made to run on any browser such as Internet Explorer, Chrome or Firefox. The Web
application would be processed on a server, which would have Internet Information Services
Installed. Internet Information Services or IIS is a Microsoft component which is used to execute
anAsp.Net application.
The Common Language Runtime (CLR) is an Execution Environment . It works as a layer between
Operating Systems and the applications written in .Net languages that conforms to the Common
Language Specification (CLS).
The main function of Common Language Runtime (CLR) is to convert the Managed Code into
native code and then execute the Program. The Managed Code compiled only when it needed,
that is it converts the appropriate instructions when each function is called .
The Common Language Runtime (CLR) 's Just In Time (JIT) compilation converts Intermediate
Language (MSIL) to native code on demand at application run time.
During the execution of the program ,the Common Language Runtime (CLR) manages memory,
Thread execution, Garbage Collection (GC) , Exception Handling, Common Type System (CTS),
code safety verifications, and other system services.
Responsibilities of CLR:
2. Code access security - CLR allows access to code to perform only those tasks for that it has
permission. It also checks user’s permissions using authentication and configuration files
of .NET applications.
4. JIT compilation - JIT stands for Just In Time. It is also an important part of Common
Language Runtime (CLR), JIT compiler converts MSIL code to targeted machine code for
execution.
Microsoft .Net Assembly is a logical unit of code, that contains code which the Common
Language Runtime (CLR) executes. It is the smallest unit of deployment of a .net application and
it can be a .dll or an exe . Assembly is really a collection of types and resource information that
are built to work together and form a logical unit of functionality. It include both executable
application files that you can run directly from Windows without the need for any other
programs (.exe files), and libraries (.dll files) for use by other applications.
Assemblies are the building blocks of .NET Framework applications. During the compile
time Metadata is created with Microsoft Intermediate Language (MSIL) and stored in a file
called Assembly Manifest . Both Metadata and Microsoft Intermediate Language (MSIL)
together wrapped in a Portable Executable (PE) file. Assembly Manifest contains information
about itself. This information is called Assembly Manifest, it contains information about the
members, types, references and all the other data that the runtime needs for execution.
Every Assembly you create contains one or more program files and a Manifest. There are two
types program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly can
have only one entry point (that is, DllMain, WinMain, or Main).
1. Private Assembly - A private Assembly is used only by a single application, and usually it is
stored in that application's install directory.
2. Shared Assembly - A shared Assembly is one that can be referenced by more than one
application.
If multiple applications need to access an Assembly, we should add the Assembly to the Global
Assembly Cache (GAC).
Satellite Assembly - A Satellite Assembly contains only static objects like images and
other non-executable files required by the application.
Uses of assemblies
i. It contains code that the common language runtime executes. Microsoft intermediate
language (MSIL) code in a portable executable (PE) file will not be executed if it does not
have an associated assembly manifest. Note that each assembly can have only one entry
point (that is, DllMain, WinMain, or Main).
ii. It forms a security boundary. An assembly is the unit at which permissions are requested
and granted.
iii. It forms a type boundary. Every type's identity includes the name of the assembly in which
it resides. A type called MyType that is loaded in the scope of one assembly is not the
same as a type called MyType that is loaded in the scope of another assembly.
iv. It forms a reference scope boundary. The assembly's manifest contains assembly
metadata that is used for resolving types and satisfying resource requests. It specifies the
types and resources that are exposed outside the assembly. The manifest also enumerates
other assemblies on which it depends.
v. It forms a version boundary. The assembly is the smallest versionable unit in the common
language runtime; all types and resources in the same assembly are versioned as a unit.
The assembly's manifest describes the version dependencies you specify for any
dependent assemblies.
vi. It forms a deployment unit. When an application starts, only the assemblies that the
application initially calls must be present. Other assemblies, such as localization resources
or assemblies containing utility classes, can be retrieved on demand. This allows
applications to be kept simple and thin when first downloaded.
The GAC is a machine-wide code cache used for side-by-side execution of assemblies. The GAC
implements the feature of shared library where different applications reuse the code placed in
the files located in a common folder.
1. GAC Tool (gacutil.exe) - GAC Tool is used to check for assembly existence, register a shared
assembly, view and manipulate contents of GAC, etc. Being a system folder, it requires
administrator privileges to be used.
2. Assembly Cache Viewer (shfusion.dll) - Assembly Cache Viewer is used to display the details
(version, culture, etc.) associated with the assemblies contained in the cache.
GAC provides the benefits of code reuse, file security (due to its installation in ‘systemroot’
directory and hence deletion is only by users with Administrator privileges), side-by-side
execution (allowing multiple versions of an assembly maintained in the same folder), etc.
An event is "something" that occurs in consequence of an action, in the given example, the action
is the button pressing. An event is a message sent by an object to signal the occurrence of an
action. The action could be caused by user interaction, such as a button click, or it could be raised
by some other program logic, such as changing a property’s value.
Events in the .NET Framework are based on the delegate model. The delegate model follows the
observer design pattern, which enables a subscriber to register with, and receive notifications
from a provider.
The objects that fire them (called event senders), however, don't know what must be done
when certain event occurs. For this is necessary to inform which method (called event handler)
will be executed at each occurrence of this event. This is not an difficult task and we do it every
day, even automatically.
To define an event, you use the event (in C#) or Event (in Visual Basic) keyword in the signature
of your event class, and specify the type of delegate for the event.
Typically, to raise an event, you add a method that is marked as protected and virtual (in C#)
or Protected and Overridable (in Visual Basic). Name this method OnEventName; for
example, OnDataReceived. The method should take one parameter that specifies an event data
object. You provide this method to enable derived classes to override the logic for raising the
event. A derived class should always call the OnEventName method of the base class to ensure
that registered delegates receive the event.
.Net Namespaces
The frameworks around them have greatly increased in size. The .NET framework provides a
huge number of base classes, data types, algorithms, etc. If every one of these items had to be
declared with a unique name, the naming task would be equally large and would leave very few
good names available for the .NET developer.
To ensure that naming conflicts do not occur, either within the .NET framework or in your own
programs, namespaces are used.
Namespaces are the way to organize .NET Framework Class Library into a logical grouping
according to their functionality, usability as well as category they should belong to, or we can
say Namespaces are logical grouping of types for the purpose of identification.
Syntax - namespace namespace-name {}
The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes. These
Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the
.NET Framework. We can uniquely identify any Class in the .NET Framework Class Library (FCL )
by using the full Namespaces of the class .In .Net languages every program is created with a
default Namespaces . Programmers can also create their own Namespaces in .Net languages.
Namespace Example
namespace FirstNamespace
{
class Test
{
public void ShowMessage()
{
Console.WriteLine("This is the first namespace!");
}}}
This code creates a new namespace named "FirstNamespace" and defines a "Test"
class containing a single method that outputs a string to the console.
A DLL is a library that contains code and data that can be used by more than one program at the
same time. By using a DLL, a program can be modularized into separate components. For example,
an accounting program may be sold by module. Each module can be loaded into the main program
at run time if that module is installed. Because the modules are separate, the load time of the
program is faster, and a module is only loaded when that functionality is requested.
Additionally, updates are easier to apply to each module without affecting other parts of the
program. For example, you may have a payroll program, and the tax rates change each year. When
these changes are isolated to a DLL, you can apply an update without needing to build or install
Types of DLLs
1. Load-time dynamic linking – In load-time dynamic linking, an application makes explicit calls to
exported DLL functions like local functions. To use load-time dynamic linking, provide a header
(.h) file and an import library (.lib) file when you compile and link the application. When you do
this, the linker will provide the system with the information that is required to load the DLL and
resolve the exported DLL function locations at load time.
Like all other .NET languages, VB.NET has complete support for object-oriented concepts.
Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long, String,
Boolean, etc.) and user-defined types, events, and even assemblies. All objects inherits from the
base class Object.
Procedures in VB.NET
A procedure is a group of logically related statements that is used to perform a specific task.
Using the concept of procedure a large application is divided into smaller units. These units are
known as procedures.
If an application contains a block of code that may executes once or more then once at that time
you can create a procedure. So instead of writing the same block of code again and again you
just have to call that procedure.
Calling a Procedure
You invoke a procedure from some other place in the code. This is known as a procedure call.
When the procedure is finished running, it returns control to the code that invoked it, which is
known as the calling code. The calling code is a statement, or an expression within a statement,
that specifies the procedure by name and transfers control to it.
Returning from a Procedure
A procedure returns control to the calling code when it has finished running. To do this, it can
use a Return Statement, the appropriate Exit Statement statement for the procedure, or the
procedure's End <keyword> Statement statement. Control then passes to the calling code
following the point of the procedure call.
Types of Procedures
1. Sub Procedures - They perform actions but do not return a value to the calling code.
A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End
Substatements. The Sub procedure performs a task and then returns control to the calling code,
but it does not return a value to the calling code.
You can define a Sub procedure in modules, classes, and structures. By default, it is Public, which
means you can call it from anywhere in your application that has access to the module, class, or
structure in which you defined it. The term, method, describes a Sub or Function procedure that
is accessed from outside its defining module, class, or structure.
Defining Sub Procedures
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
Modifiers − specify the access level of the procedure; possible values are - Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing,
and shadowing.
SubName − indicates the name of the Sub
ParameterList − specifies the list of the parameters
Passing Parameters by Value
This is the default mechanism for passing parameters to a method. In this mechanism, when a
method is called, a new storage location is created for each value parameter. The values of the
actual parameters are copied into them. So, the changes made to the parameter inside the
method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByVal keyword.
Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable. When you pass
parameters by reference, unlike value parameters, a new storage location is not created for
these parameters. The reference parameters represent the same memory location as the actual
parameters that are supplied to the method.
In VB.Net, you declare the reference parameters using the ByRef keyword.
2. Function Procedures - - They return a value to the calling code. They can perform other
actions before returning.
A Function procedure is a series of Visual Basic statements enclosed by the Function and End
Function statements. The Function procedure performs a task and then returns control to the
calling code. When it returns control, it also returns a value to the calling code.
You can define a Function procedure in a module, class, or structure. It is Public by default,
which means you can call it from anywhere in your application that has access to the module,
class, or structure in which you defined it.
Declaration Syntax
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Event-handling procedures are Sub procedures that execute in response to an event raised by
user action or by an occurrence in a program.
Class A container for data and code. The data within the class can be accessed with properties.
The code is referred to as methods.
Object An instance of a class in memory. An instance is created using a Dim statement and
the New keyword.
Creating Properties
To create a property within a class, you can either create a field (ie. a Public variable), or you can
create a Private variable and expose the Private variable using a Property statement. There are
several reasons why you want to only expose properties through a Property statement.
You can create a read-only or write-only property, as opposed to a Public variable, which will
always be read-write.
You can add error handling within a Property statement to check for invalid values being set..
You can expose calculated values as properties even if they are not stored as actual data within
the class. An example of this is a Length property. You probably don't want to store the length
of a line of text, as it could change.
Inheritance
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance is the idea that one class, called a subclass, can be based on another class, called a
base class. Inheritance provides a mechanism for creating hierarchies of objects.
For example, a dog is a mammal and a collie is a dog. Thus the dog class inherits the properties
and methods of the mammalclass, and the collie class inherits from both dog and mammal.
The objects in a hierarchy have two different types of relationships to one another, referred to
in object-oriented parlance as HasA and IsA relationships. For example, a Collie IsA dog and
HasA tail.
When creating a class, instead of writing completely new data members and member functions,
the programmer can designate that the new class should inherit the members of an existing
class. This existing class is called the baseclass, and the new class is referred to as
the derived class.
Base & Derived Classes
A class can be derived from more than one class or interface, which means that it can inherit
data and functions from multiple base classes or interfaces. Syntax -
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Inheritance Modifiers
By default, a derived class inherits properties and methods from its base class. If an inherited
property or method has to behave differently in the derived class it can be overridden. That is,
you can define a new implementation of the method in the derived class. The following
modifiers are used to control how properties and methods are overridden:
The MyBase keyword behaves like an object variable that refers to the base class of the current
instance of a class. MyBase is frequently used to access base class members that are overridden
or shadowed in a derived class. In particular, MyBase.New is used to explicitly call a base class
constructor from a derived class constructor.
The MyClass Keyword
The MyClass keyword behaves like an object variable that refers to the current instance of a
class as originally implemented. MyClass resembles Me, but every method and property call
on MyClassis treated as if the method or property were NotOverridable. Therefore, the method
or property is not affected by overriding in a derived class.
Interfaces in VB.NET
Interfaces define the properties, methods, and events that classes can implement. Interfaces
allow you to define features as small groups of closely related properties, methods, and events;
this reduces compatibility problems because you can develop enhanced implementations for
your interfaces without jeopardizing existing code. You can add new features at any time by
developing additional interfaces and implementations.
Declaring Interfaces
Interface definitions are enclosed within the Interface and End Interface statements. Following
the Interface statement, you can add an optional Inherits statement that lists one or more
inherited interfaces. The Inherits statements must precede all other statements in the
declaration except comments. The remaining statements in the interface definition should
be Event, Sub, Function, Property, Interface, Class, Structure, and Enum statements. Interfaces
cannot contain any implementation code or statements associated with implementation code,
such as End Sub or End Property.
In a namespace, interface statements are Friend by default, but they can also be explicitly
declared as Public or Friend. Interfaces defined within classes, modules, interfaces, and
structures are Public by default, but they can also be explicitly declared
as Public, Friend, Protected, or Private.
Implementing Interfaces - The Visual Basic reserved word Implements is used in two ways-
Interface Inheritance
Interfaces support inheritance too. You can define an interface and define a second interface
that inherits from the original interface. By adding new interface members to the new interface,
you can extend the definition of an interface or inherit from multiple interfaces.
Delegates in VB.NET
A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class
has a signature, and it can hold references only to methods that match its signature. Delegates
are similar to function pointers in C, C++. Delegates are objects that refer to methods. They are
sometimes described as type-safe function pointers because they are similar to function
pointers used in other programming languages. But unlike function pointers, Visual Basic
delegates are a reference type based on the class System.Delegate. Delegates can reference
both shared methods — methods that can be called without a specific instance of a class — and
instance methods.
Events in VB.NET are handled by delegates, which serve as a mechanism that defines one or
more callback functions to process events.
Although you can create your own delegates, in most cases Visual Basic creates the delegate and
takes care of the details for you. For example, an Event statement implicitly defines a delegate
class named <EventName>EventHandler as a nested class of the class containing
the Eventstatement, and with the same signature as the event. The AddressOf statement
implicitly creates an instance of a delegate that refers to a specific procedure.
VB.NET – List
The List type belongs to a group that we call generic collections. List can store only one type of
objects, that type supplied as its generic parameter. List class is a collection and defined in the
System.Collections.Generic namespace and it provides the methods and properties like other
Collection classes such as add, insert, remove, search etc.
To use List(Of T), however, you have to understand how to implement the many methods that
the .NET Framework provides
List(Of T)
Add integer values in the List - Dim iList As New List(Of Integer)()
iList.Add(2)
Add string values in the List - Dim numbers As New List(Of String)()
numbers.Add("One")
List methods
Add(item) - This method takes an item as a parameter and adds to the end of the list.
AddRange(collection) - Adds multiple items to the list, e.g. from an array.
Clear() - Removes all items in the List.
Contains(item) - Returns true/false depending on whether the List contains the given item.
CopyTo(array) - Copies all items in the list to a given array. We can specify the starting index and
the number of items.
IndexOf(item) - Returns the index of the first occurrence of a given item in the list (like with an
array). Returns -1 in case of failure.
Insert(index, item) - Inserts an item at the given index, position, in the List.
InsertRange(index, collection) - Inserts multiple items from the collection at the given index in
the List.
LastIndexOf(item) - Returns the index of the last occurrence of a given item in the list. Returns -1
in case of failure.
Remove(item) - Removes the first occurrence of an item.
RemoveAt(index) - Removes the item at the specified index.
RemoveRange(index, count) - Removes a specified number of items starting at a specific index.
Reverse() - Works the same as it would in an array. It reverses the List so the first item is the last
and vice versa. The method doesn't return anything, the changes are made directly to the List.
Sort() - This method sorts the items in the List. The method doesn't return anything either.
ToArray() - Copies the items from the List to a given array and returns it.
Average() - Returns the average of the items in the List as a double.
Distinct() - Returns all of the items of which there is only one instance in the List.
First() - Returns the first item.
Last() - Returns the last item.
Intersect(collection) - Returns the intersection of the List with the specified collection.
Union() - Returns the union of the List with the specified collection.
Min() - Returns the smallest element.
Max() - Returns the largest element.
Sum() - Returns the sum of the elements
VB.Net - Collections
Collection classes are specialized classes for data storage and retrieval. These classes provide
support for stacks, queues, lists, and hash tables. Most collection classes implement the same
interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to elements
and accessing a list of items on the basis of an index, etc. These classes create collections of
objects of the Object class, which is the base class for all data types in VB.Net.
A collection is a class, so you must declare an instance of the class before you can add elements
to that collection.
If your collection contains elements of only one data type, you can use one of the classes in
the System.Collections.Generic namespace. A generic collection enforces type safety so that no
other data type can be added to it. When you retrieve an element from a generic collection, you
do not have to determine its data type or convert it.
Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the form of try and
catch blocks. Using these blocks the core program statements are separated from the error-
handling statements.
These error handling blocks are implemented using the Try, Catch and Finally keywords.
Creating User-Defined Exceptions
You can also define your own exception. User-defined exception classes are derived from
the ApplicationException class.
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception
class.You can use a throw statement in the catch block to throw the present object as −
Throw [ expression ]
Multithreading - VB.NET
Multithreading is a type of execution model that allows multiple threads to exist within the
context of a process such that they execute independently but share their process resources. A
thread maintains a list of information relevant to its execution including the priority schedule,
exception handlers, a set of CPU registers, and stack state in the address space of its hosting
process.
Multithreading is also known as threading
Vc #.net
Source code written in C# is compiled into an intermediate language (IL) that conforms to the CLI
specification. The IL code and resources, such as bitmaps and strings, are stored on disk in an
executable file called an assembly, typically with an extension of .exe or .dll. An assembly
contains a manifest that provides information about the assembly's types, version, culture, and
security requirements.
C# - Data Types
Variables - A variable can be compared to a storage room, and is essential for the programmer.
In C#, a variable is declared like this: <visibility> <data type> <name> = <value>;
ii. Dynamic Type - You can store any type of value in the dynamic data type variable. Type
checking for these types of variables takes place at run-time. dynamic d = 20;
iii. String Type - The String Type allows you to assign any string values to a variable. The string type is
an alias for the System.String class. It is derived from object type. The value for a string type can
be assigned using string literals in two forms: quoted and @quoted.
3. Pointer Type - Pointer type variables store the memory address of another type. Pointers in C#
have the same capabilities as the pointers in C or C++.
C# - Classes
When you define a class, you define a blueprint for a data type. This does not actually define any
data, but it does define what the class name means. That is, what an object of the class consists
of and what operations can be performed on that object. Objects are instances of a class. The
methods and variables that constitute a class are called members of the class.
Defining a Class
using System; car = new Car("Red");
namespace ConsoleApplication1 Console.WriteLine(car.Describe());
{ car = new Car("Green");
class Program
{ Console.WriteLine(car.Describe());
static void Main(string[] args)
{ Console.ReadLine();
Car car; }
}
Member Functions and Encapsulation
A member function of a class is a function that has its definition or its prototype within the class
definition similar to any other variable. It operates on any object of the class of which it is a
member, and has access to all the members of a class for that object.
Member variables are the attributes of an object (from design perspective) and they are kept
private to implement encapsulation. These variables can only be accessed using the public
member functions.
C# Constructors
A class constructor is a special member function of a class that is executed whenever we create
new objects of that class.
A constructor has exactly the same name as that of class and it does not have any return type.
A default constructor does not have any parameter but if you need, a constructor can have
parameters. Such constructors are called parameterized constructors. This technique helps you
to assign initial value to an object at the time of its creation
C# Destructors
A destructor is a special member function of a class that is executed whenever an object of its
class goes out of scope. A destructor has exactly the same name as that of the class with a
prefixed tilde (~) and it can neither return a value nor can it take any parameters.
Destructor can be very useful for releasing memory resources before exiting the program.
Destructors cannot be inherited or overloaded.
You can also declare a member function as static. Such functions can access only static variables.
The static functions exist even before the object is created.
using System;
namespace StaticVarApplication {
class StaticVar {
num++;
return num;
C# - Method overloading
Overloaded methods are differentiated based on the number and type of the parameters
passed as arguments to the methods.
You can not define more than one method with the same name, Order and the type of the
arguments. It would be compiler error.
The compiler does not consider the return type while differentiating the overloaded method.
But you cannot declare two methods with the same signature and different return type. It will
throw a compile-time error. If both methods have the same parameter types, but different
return type, then it is not possible.
Delegates provide a way to define and execute callbacks. Their flexibility allows you to define
the exact signature of the callback, and that information becomes part of the delegate type
itself. Delegates are type-safe, object-oriented and secure.
The delegate contains a couple of useful fields. The first one holds a reference to an object, and
the second holds a method pointer. When you invoke the delegate, the instance method is
called on the contained reference.
However, if the object reference is null then the runtime understands this to mean that the
method is a static method. Moreover, invoking a delegate syntactically is the exact same as
calling a regular function. Therefore, delegates are perfect for implementing callbacks.
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate. A
delegate can refer to a method, which has the same signature as that of the delegate.
Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with the new keyword and
be associated with a particular method. When creating a delegate, the argument passed to
the new expression is written similar to a method call, but without the arguments to the
method. For example −
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
Multicasting of a Delegate
Delegate objects can be composed using the "+" operator. A composed delegate calls the two
delegates it was composed from. Only delegates of the same type can be composed. The "-"
operator can be used to remove a component delegate from a composed delegate.
Using this property of delegates you can create an invocation list of methods that will be called
when a delegate is invoked. This is called multicasting of a delegate.
2. Events - Events are user actions such as key press, clicks, mouse movements, etc., or some
occurrence such as system generated notifications. Applications need to respond to events
when they occur. For example, interrupts. Events are used for inter-process communication.
C# - Interfaces
An interface is defined as a syntactical contract that all the classes inheriting the interface
should follow. The interface defines the 'what' part of the syntactical contract and the deriving
classes define the 'how' part of the syntactical contract.
Interfaces define properties, methods, and events, which are the members of the interface.
Interfaces contain only the declaration of the members. It is the responsibility of the deriving
class to define the members. It often helps in providing a standard structure that the deriving
classes would follow.
Abstract classes to some extent serve the same purpose, however, they are mostly used when
only few methods are to be declared by the base class and the deriving class implements the
functionalities.
Declaring Interfaces
Interfaces are declared using the interface keyword. It is similar to class declaration. Interface
statements are public by default. Following is an example of an interface declaration −
// interface members
void showTransaction();
double getAmount();
System.Collections Namespace
The System.Collections namespace contains interfaces and classes that define various
collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.
Classes
ArrayList Implements the IList interface using an array whose size is
dynamically increased as required.
BitArray 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).
CaseInsensitiveComparer Compares two objects for equivalence, ignoring the case of strings.
CaseInsensitiveHashCode Supplies a hash code for an object, using a hashing algorithm that
Provider ignores the case of strings.
CollectionBase Provides the abstract base class for a strongly typed collection.
Comparer Compares two objects for equivalence, where string comparisons
are case-sensitive.
DictionaryBase Provides the abstract base class for a strongly typed collection of
key/value pairs.
Hashtable Represents a collection of key/value pairs that are organized based
on the hash code of the key.
Queue Represents a first-in, first-out collection of objects.
ReadOnlyCollectionBase Provides the abstract base class for a strongly typed non-generic
read-only collection.
SortedList Represents a collection of key/value pairs that are sorted by the
keys and are accessible by key and by index.
Stack Represents a simple last-in-first-out (LIFO) non-generic collection of
objects.
StructuralComparisons Provides objects for performing a structural comparison of two
collection objects.
C# - Queue And Stacks
1. Stack in C# - Stack is a linear data structure. It follows LIFO(Last In First Out) pattern for
Input/output. Following three basic operations are performed in the stack:
Push: Adds an item in the stack. If the stack is full, then it is said to be a stack Overflow
condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they
are pushed. If the stack is empty, then it is said to be a stack Underflow condition.
Peek : Return the topmost element of stack.
Declaration of the stack
A stack is created with the help of the Stack Data type. The keyword "new" is used to create an
object of a Stack. The object is then assigned to the variable st.
2. Queue in C# - The Queue is a special case collection which represents a first in first out concept. It
represents a first-in, first out collection of object. It is used when you need a first-in, first-out
access of items. When you add an item in the list, it is called enqueue, and when you remove an
item, it is called deque. (Methods same as stack )
File System
A file is a collection of data stored in a disk with a specific name and a directory path. When a
file is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path. There
are two main streams: the input stream and the output stream. The input stream is used for
reading data from file (read operation) and the output stream is used for writing into the file
(write operation).
File and stream I/O (input/output) refers to the transfer of data either to or from a storage
medium. In the .NET Framework, the System.IO namespaces contain types that enable reading
and writing, both synchronously and asynchronously, on data streams and files. These
namespaces also contain types that perform compression and decompression on files, and types
that enable communication through pipes and serial ports.
When you work with files, you work with directory paths, disk storage, and file and directory
names. In contrast, a stream is a sequence of bytes that you can use to read from and write to a
backing store, which can be one of several storage mediums (for example, disks or memory).
Just as there are several backing stores other than disks, there are several kinds of streams other
than file streams, such as network, memory, and pipe streams.
Definition of a Stream
The .NET Framework uses streams to support reading from and writing to files.
You can think of a stream as a one-dimensional set of contiguous data, which
has a beginning and an end, and where the cursor indicates the current
position in the stream.
Stream Operations
The data contained in the stream may come from memory, a file, or a TCP/IP socket. Streams have
fundamental operations that can be applied to them:
Reading. You can read from a stream, transferring data from the stream into a data structure,
such as a string or an array of bytes.
Writing. You can write to a stream, transferring data from a data source into the stream.
Seeking. You can query and modify your position in the stream.
1. The StreamReader Class - The StreamReader class also inherits from the abstract base class
TextReader that represents a reader for reading series of characters. methods of the
StreamReader class –
Method Name & Purpose
Public Overrides Sub Close
It closes the StreamReader object and the underlying stream and
releases any system resources associated with the reader.
Public Overrides Function Peek As Integer
Returns the next available character but does not consume it.
Public Overrides Function Read As Integer
Reads the next character from the input stream and advances the
character position by one character.
2. The StreamWriter Class - The StreamWriter class inherits from the abstract class TextWriter that
represents a writer, which can write a series of character. Methods of this class −
Method Name & Purpose
Public Overrides Sub Close
Closes the current StreamWriter object and the underlying stream.
Public Overrides Sub Write (value As Char)
Writes a character to the stream.
Public Overridable Sub Write (value As Decimal)
Writes the text representation of a decimal value to the text string or
stream.
Public Overrides Sub Write (value As String)
Writes a string to the stream.
Public Overridable Sub WriteLine
Writes a line terminator to the text string or stream.
ADO.NET Architecture
ADO is the acronym for ActiveX Data Object and is a Microsoft technology. ADO .NET is a
data access and manipulation protocol. Many applications need data access at one point
of time making it a crucial component when working with applications. Data access is
making the application interact with a database, where all the data is stored. Different
applications have different requirements for database access.
ADO.NET provides a bridge between the front end controls and the back end database. The
ADO.NET objects encapsulate all the data access operations and the controls interact with these
objects to display data, thus hiding the details of movement
of data.
The two key components of ADO.NET are Data Providers and DataSet .
1. Data Providers - The Data Provider classes are meant to work with different kinds of data
sources. They are used to perform all data-management operations on specific databases.
The .Net Framework includes mainly three Data Providers for ADO.NET. They are the Microsoft
SQL Server Data Provider , OLEDB Data Provider and ODBC Data Provider . SQL Server uses the
SqlConnection object , OLEDB uses the OleDbConnection Object and ODBC uses OdbcConnection
Object respectively.
A data provider contains Connection, Command, DataAdapter, and DataReader objects. These
four objects provides the functionality of Data Providers in the ADO.NET.
i. Connection - The Connection Object provides physical connection to the Data Source.
Connection object needs the necessary information to recognize the data source and to log
on to it properly, this information is provided through a connection string.
ii. Command - The Command Object uses to perform SQL statement or stored procedure to be
executed at the Data Source. The command object provides a number of Execute methods
that can be used to perform the SQL queries in a variety of fashions.
iv. DataAdapter - DataAdapter Object populate a Dataset Object with results from a Data
Source . It is a special class whose purpose is to bridge the gap between the disconnected
Dataset objects and the physical data source.
The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is essentially
the middleman facilitating all communication between the database and a DataSet. The
DataAdapter is used either to fill a DataTable or DataSet with data from the database with it's
Fill method. After the memory-resident data has been manipulated, the DataAdapter can
commit the changes to the database by calling the Update method. The DataAdapter provides
four properties that represent database commands:
SelectCommand
InsertCommand
DeleteCommand
UpdateCommand
When the Update method is called, changes in the DataSet are copied back to the database and
the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed.
2. DataSet - DataSet class provides mechanisms for managing data when it is disconnected from
the data source.
DataSet provides a disconnected representation of result sets from the Data Source, and it is
completely independent from the Data Source. DataSet provides much greater flexibility when
dealing with related Result Sets.
DataSet contains rows, columns,primary keys, constraints, and relations with other DataTable
objects. It consists of a collection of DataTable objects that you can relate to each other with
DataRelation objects. The DataAdapter Object provides a bridge between the DataSet and the
Data Source.
ADO.NET connects to the database to retrieve data, and connects again to update data when
you’ve made changes. Most applications spend most of their time simply reading through data
and displaying it; ADO.NET provides a disconnected subset of the data for your use while
reading and displaying.
DataGrid - The Windows Forms DataGrid control provides a user interface to ADO.NET datasets,
displays ADO.NET tabular data in a scrollable grid, and allows for updates to the data source. In
cases where the DataGrid is bound to a data source with a single table containing no
relationships, the data appears in simple rows and columns, as in a spreadsheet.
The DataGrid control is one of the most useful and flexible controls in Windows Forms. As soon as
the DataGrid control is set to a valid data source, the control is automatically populated, by
creating columns and rows based on the structure of the data. The DataGrid control can be used
to display either a single table or the hierarchical relationships between a set of tables. Valid data
sources for the DataGridinclude:
DataTable
DataView
DataSet
DataViewManager
A single dimension array
Any component that implements the IListSource interface.
How It Works?After you get connected to the MS Access database, all records are displayed on
the DataGrid. When you run the application first time, the method "fnRefresh()" will be called. It
clears the contents of the DataSet, fills the DataAdapter, and displays the data from the data
source in the DataGrid. After that, all the buttons are ready to be used.
Use of data adapter.
- They provide the means for the exchange of data between the data store and the tables in the
DataSet.
- Data adapters are an integral part of ADO.NET managed providers, which are the set of objects
used to communicate between a data source and a dataset.
- Adapters are used to exchange data between a data source and a dataset.
- In many applications, this means reading data from a database into a dataset, and then writing
changed data from the dataset back to the database.
- However, a data adapter can move data between any source and a dataset.