C# ADO - Net Notes Final Prints
C# ADO - Net Notes Final Prints
Net
Framework
C# Programming
& ADO.Net
www.enosislearning.com
courses@enosislearning.com
Table of Contents
What is the .NET Platform? ............................................................................................................................................ 7
What is the .NET Framework? ....................................................................................................................................... 7
.NET Framework Components ............................................................................................................................. 8
.NET Framework Architecture ............................................................................................................................. 8
Common Language Runtime (CLR)................................................................................................................................. 9
Responsibilities of CLR ......................................................................................................................................... 9
CLR Architecture ................................................................................................................................................ 10
Managed and Unmanaged Code ....................................................................................................................... 10
Managed Code ......................................................................................................................................... 10
Unmanaged (Win32) Code....................................................................................................................... 11
Memory Management....................................................................................................................................... 11
Intermediate Language (MSIL, IL, CIL) ......................................................................................................................... 11
Compilation and Execution .......................................................................................................................................... 12
Common Type System (CTS) ........................................................................................................................................ 12
Common Language Infrastructure (CLI) ....................................................................................................................... 13
Common Language Specification (CLS) ........................................................................................................................ 13
Framework Class Library (FCL) ..................................................................................................................................... 13
.NET Applications (Assemblies, Metadata, Applications) ........................................................................................... 14
.NET Assemblies ................................................................................................................................................. 14
Metadata in the Assemblies .............................................................................................................................. 14
Namespace ........................................................................................................................................................ 15
Global assembly cache (GAC) ............................................................................................................................ 15
.NET Applications ............................................................................................................................................... 15
.NET Languages ............................................................................................................................................................. 15
C# Language .................................................................................................................................................................. 16
C# Data Types ............................................................................................................................................................... 16
Value Type and Reference Type................................................................................................................................... 17
Value Type ......................................................................................................................................................... 17
Pass By Value .......................................................................................................................................... 17
Reference Type ................................................................................................................................................. 18
Pass By Reference .................................................................................................................................... 18
Datatype conversions ................................................................................................................................................... 19
Implicit Conversion ............................................................................................................................................ 19
Explicit Conversion............................................................................................................................................. 19
Difference between Parse and TryParse ................................................................................................. 20
Access Modifier Keywords ........................................................................................................................................... 22
Operators ...................................................................................................................................................................... 23
Arithmetic Operators ......................................................................................................................................... 23
Relational Operators.......................................................................................................................................... 23
Logical Operators ............................................................................................................................................... 24
www.enosislearning.com
Page 2
Bitwise Operators .............................................................................................................................................. 24
Assignment Operators ....................................................................................................................................... 25
Miscellaneous Operators ................................................................................................................................... 26
Decision Making ........................................................................................................................................................... 27
if statement ....................................................................................................................................................... 27
if-else Statement ............................................................................................................................................... 27
else if Statement ................................................................................................................................................ 28
Nested if Statements ......................................................................................................................................... 28
Ternary operator ?:............................................................................................................................................ 29
Nested Ternary operator: ........................................................................................................................ 29
Switch Case ........................................................................................................................................................ 30
Goto in switch: ......................................................................................................................................... 30
Loops ............................................................................................................................................................................. 31
for loop .............................................................................................................................................................. 31
while loop: ......................................................................................................................................................... 32
do while ............................................................................................................................................................. 33
Array ............................................................................................................................................................................. 34
Declaring Arrays ..................................................................................................................................................... 34
Initializing an Array ................................................................................................................................................. 34
Assigning Values to an Array .................................................................................................................................... 34
Multi-dimensional Array .................................................................................................................................... 35
Jagged Array ...................................................................................................................................................... 36
Methods ........................................................................................................................................................................ 37
Calling Methods in C# ............................................................................................................................................. 37
Method Parameters ..................................................................................................................................................... 38
Value Parameter ................................................................................................................................................ 38
Reference Parameter......................................................................................................................................... 38
Output Parameter ............................................................................................................................................. 38
Parameter Arrays ............................................................................................................................................... 39
Enum ............................................................................................................................................................................. 39
Enum methods: ................................................................................................................................................. 39
Classes ........................................................................................................................................................................... 41
Members of Class .............................................................................................................................................. 41
Constructor ........................................................................................................................................................ 42
Destructor .......................................................................................................................................................... 42
Member Functions and Encapsulation .............................................................................................................. 42
Static And Instance Class Members ................................................................................................................... 43
Static Constructor .............................................................................................................................................. 43
Copy Constructor ............................................................................................................................................... 44
Private Constructor............................................................................................................................................ 45
Properties ..................................................................................................................................................................... 45
www.enosislearning.com
Page 3
Creating Read-Only Properties .......................................................................................................................... 46
Creating a Write-Only Property ......................................................................................................................... 47
Creating Auto-Implemented Properties ............................................................................................................ 48
Inheritence.................................................................................................................................................................... 50
THIS & NEW KEYWORD...................................................................................................................................... 51
Interface........................................................................................................................................................................ 53
Abstract Class ............................................................................................................................................................... 55
Important rules applied to abstract classes ...................................................................................................... 56
Abstract class vs. Interface : .............................................................................................................................. 57
DIFFERENCE BETWEEN INTERFACE & ABSTRACT CLASS.................................................................................... 57
Struct ............................................................................................................................................................................. 58
DIFFERENCE BETWEEN STRUCTURE AND CLASS ............................................................................................... 59
Partial Classes ............................................................................................................................................................... 60
Sealed Classes ............................................................................................................................................................... 61
Static Class .................................................................................................................................................................... 63
Extention Methods ....................................................................................................................................................... 66
Important Points of Static.................................................................................................................................. 65
Encapsulation ............................................................................................................................................................... 67
Polymorphism............................................................................................................................................................... 67
Method Hiding ................................................................................................................................................... 69
Method Overriding(RunTime Polymorphism) ................................................................................................... 70
Differences Among Method Overriding, Method Hiding (new Keyword) and Method Shadowing in C# ........ 71
Abstraction ................................................................................................................................................................... 73
Difference between Abstraction and Encapsulation ......................................................................................... 74
Exception in C# ............................................................................................................................................................. 74
Exception Handling ............................................................................................................................................ 75
Throwing Exceptions (the throw Construct)...................................................................................................... 76
Delegate ........................................................................................................................................................................ 77
Multicast Delegate............................................................................................................................................. 78
Array of Delegates ............................................................................................................................................. 78
Anonymous Methods ........................................................................................................................................ 79
Event ............................................................................................................................................................................. 80
Event Arguments ............................................................................................................................................... 83
Generics ........................................................................................................................................................................ 85
Generic Delegates.............................................................................................................................................. 86
Generic Type Parameters .................................................................................................................................. 87
Constraints on type parameters ........................................................................................................................ 87
Attribute ....................................................................................................................................................................... 88
Predefined Attributes ........................................................................................................................................ 89
AttributeUsage ......................................................................................................................................... 89
Conditional ............................................................................................................................................... 90
www.enosislearning.com
Page 4
Obsolete ................................................................................................................................................... 91
Creating Custom Attributes ............................................................................................................................... 91
Reflection ...................................................................................................................................................................... 92
Collection ...................................................................................................................................................................... 94
ArrayList ............................................................................................................................................................. 95
Properties and Methods of ArrayList ................................................................................................................ 95
SortedList ........................................................................................................................................................... 96
Properties and Methods of SortedList............................................................................................................... 96
Stack................................................................................................................................................................... 96
Properties and Methods of Stack: ..................................................................................................................... 97
Queue ................................................................................................................................................................ 97
Properties and Methods of Queue: ................................................................................................................... 97
Hashtable ........................................................................................................................................................... 97
Propertis and Methods of Hashtable ................................................................................................................ 98
Multithreading.............................................................................................................................................................. 98
Features and Benefits of Threads ...................................................................................................................... 98
Properties and Methods of the Thread Class ............................................................................................................... 99
File Handling ............................................................................................................................................................... 104
Working with Directories ................................................................................................................................. 104
DirectoryInfo Class ................................................................................................................................. 105
Directory Class ....................................................................................................................................... 105
Reading and Writing to Files ............................................................................................................................ 106
Stream ............................................................................................................................................................. 107
FileStream .............................................................................................................................................. 107
BinaryReader and BinaryWriter....................................................................................................................... 108
StringReader and StringWriter ........................................................................................................................ 109
Introduction to ADO.Net ............................................................................................................................................ 111
What are .NET Data Providers? ....................................................................................................................... 112
SQLConnection in ADO.NET ............................................................................................................................ 113
Connection Strings in web.config configuration file........................................................................................ 115
SqlCommand in ado.net ............................................................................................................................................. 117
Sql injection ................................................................................................................................................................ 119
Sql Injection prevention using “Parametrized Queries”.................................................................................. 120
Sql Injection prevention using “Stored Procedure” ........................................................................................ 120
Calling a stored procedure with output parameters ....................................................................................... 121
SqlDataReader object in ADO.NET............................................................................................................................. 122
Read() Method of SqlDataReader.................................................................................................................... 123
NextResult() method Of SqlDataReader .......................................................................................................... 124
SqlDataAdapter in ADO.NET ...................................................................................................................................... 125
DataSet in ADO.Net .................................................................................................................................................... 127
SqlCommandBuilder ................................................................................................................................................... 132
www.enosislearning.com
Page 5
www.enosislearning.com
Page 6
What is the .NET Platform?
The .NET platform
Microsoft's platform for software development
Unified technology for development of almost any kind of applications
GUI / Web / RIA / mobile / server / cloud / etc.
.NET platform versions
.NET Framework
Silverlight / Windows Phone 7
.NET Compact Framework
.NET framework is a Windows Component that supports the building and running of windows
applications, web and XML Web services. The purpose of the component is to provide the user with a
consistent object oriented programming environment whether the code is stored locally or remotely.
It aims to minimize software deployment and versioning conflicts and also promote safe execution of
code including codes executed by trusted third parties. It is directed towards eliminating performance
problems of scripted or interpreted environments. The effort is to make developer experience consistent
across a variety of applications and platforms and create communication standards that help .NET
framework applications integrate with all other web based applications
www.enosislearning.com
Page 7
.NET Framework Components
The .NET framework has two major components-- The Common Runtime (CLR) and the Class Library
Common Language Runtime (CLR)
The CLR is the foundation upon which the .NET Framework has been built. The runtime
manages code at execution time and provides all the core services such as memory
management, thread management and remoting. This capability to manage code at
runtime is the distinguishing feature of the CLR. All code that is managed by the CLR is
known as managed code while other codes are known as unmanaged code.
www.enosislearning.com
Page 8
The OS manages the resources, the processes and the users of the machine
Provides to the applications some services (threads, I/O, GDI+, DirectX, COM, COM+, MSMQ, IIS, WMI,
…)
CLR is a separate process in the OS
CLR manages the execution of the.NET code
Manages the memory, concurrency, security,
Rich object-oriented library with fundamental classes
Input-output, collections, text processing, networking, security, multi-threading, …
Database access
ADO.NET, LINQ, LINQ-to-SQL and Entity Framework
Strong XML support
Windows Communication Foundation (WCF) and Windows Workflow Foundation (WWF) for the SOA
world
User interface technologies: Web based, Windows GUI, WPF, Silverlight, mobile, …
Programming language on your flavor!
Responsibilities of CLR
Execution of the IL code and the JIT compilation
Managing memory and application resources
Ensuring type safety
Interaction with the OS
Managing security
Code access security
Role-based security
Managing exceptions
www.enosislearning.com
Page 9
Managing concurrency – controlling the parallel execution of application threads
Managing application domains and their isolation
Interaction with unmanaged code
Supporting debug / profile of .NET code
CLR Architecture
Managed Code
CLR executed code is called managed code
Represents programming code in the low level language MSIL (MS Intermediate Language)
Contains metadata
Description of classes, interfaces, properties, fields, methods, parameters, etc.
Programs, written in any .NET language are
Compiled to managed code (MSIL)
Packaged as assemblies (.exe or .dll files)
Object-oriented
Secure
Reliable
Protected from irregular use of types (type-safe)
Allows integration between components and data types of different programming languages
www.enosislearning.com
Page 10
Portable between different platforms
Windows, Linux, Max OS X, etc.
Memory Management
CLR manages memory automatically
Dynamically loaded objects are stored in the managed heap
Unusable objects are automatically cleaned up by the garbage collector
Some of the big problems are solved
Memory leaks
Access to freed or unallocated memory
Objects are accessed through a reference
www.enosislearning.com
Page 11
Compilation and Execution
A number of types are supported by the CLR and are described by the CTS. Both value types are
supported—primitive data types and reference types. The primitive data types include Byte, Int16,
Double and Boolean while Reference types include arrays, classes and object and string types. Reference
types are types that store a reference to the location of their values. The value is stored as part of a
defined class and is referenced through a class member on the instance of a class.
User defined value types and enumerations are derived from the value types mentioned above.
Language compilers implement types using their own terminology.
CTS defines the CLR supported types of data and the operations over them
Ensures data level compatibility between different .NET languages
www.enosislearning.com
Page 12
E.g. string in C# is the same like String in VB.NET and in J#
Value types and reference types
A subset of the .NET framework is the CLI. The CLI includes the functionality of the Common Language
Runtime and specifications for the Common Type System, metadata and Intermediate language.
The Class Library is an object oriented collection of reusable types. Unmanaged components that
load CLR into their processes can be hosted by the .NET Framework to initiate the execution of managed
code. This creates a software environment that exploits both the managed and unmanaged codes.
The.NET Framework also provides a number of runtime hosts and supports third party runtime hosts
Class Library Features :
www.enosislearning.com
Page 13
1. The class library is a collection of reusable types that integrate with the CLR.
2. It is object oriented and provides types from which user defined types can derive functionality. This
makes for ease of use and is time saving.
3. It supports a variety of specialized development scenarios such as console application development,
Windows GUI applications, ASP.NET Applications, XML Web services.
.NET Assemblies
Assembly is a single deployable unit that contains all the information about the classes, structure,
and interface. Assemblies store all the information about itself. This information can be called metadata.
It is physical grouping of logical units, . Namespace can span multiple assemblies.
Assemblies can be private & public
.NET assemblies:
Self-containing .NET components
Stored in .DLL and .EXE files
Contain list of classes, types and resources
Smallest deployment unit in CLR
Have unique version number
.NET deployment model
No version conflicts (forget the "DLL hell")
Supports side-by-side execution of different versions of the same assembly
www.enosislearning.com
Page 14
Namespace
It is logically group classes. It avoid any naming conflicts between classes which have same name.
It allows u to organize your classes so that they can be easily accessed in other application.
.NET Applications
Configurable executable .NET units
Consist of one or more assemblies
Installed by "copy / paste"
No complex registration of components
Different applications use different versions of common assemblies
No conflicts due to their "strong name"
Easy installation, un-installation and update
.NET Languages
.NET languages by Microsoft
C#, VB.NET, Managed C++, J#, F#, JScript
.NET languages by third parties
www.enosislearning.com
Page 15
Object Pascal, Perl, Python, COBOL, Haskell, Oberon, Scheme, Smalltalk…
Different languages can be mixed in a single application
Cross-language inheritance of types and exception handling
C# Language
C# is mixture between C++, Java and Delphi
Fully object-oriented by design
Component-oriented programming model
Components, properties and events
No header files like C/C++
Suitable for GUI and Web applications
XML based documentation
In C# all data types are objects
Example: 5.ToString() is a valid call
C# Data Types
The data type tells the C# compiler what kind of value a variable can hold. C# includes many in-built data
types for different kinds of data, e.g. String, number, float, decimal, etc.
.NET Size
Alias Type Type (bits) Range (values)
byte Byte Unsigned integer 8 0 to 255
sbyte SByte Signed integer 8 -128 to 127
int Int32 Signed integer 32 -2,147,483,648 to 2,147,483,647
uint UInt32 Unsigned integer 32 0 to 4294967295
short Int16 Signed integer 16 -32,768 to 32,767
ushort UInt16 Unsigned integer 16 0 to 65,535
long Int64 Signed integer 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
ulong UInt64 Unsigned integer 64 0 to 18,446,744,073,709,551,615
float Single Single-precision floating point type 32 -3.402823e38 to 3.402823e38
double Double Double-precision floating point type 64 -1.79769313486232e308 to
1.79769313486232e308
char Char A single Unicode character 16 Unicode symbols used in text
www.enosislearning.com
Page 16
.NET Size
Alias Type Type (bits) Range (values)
bool Boolean Logical Boolean type 8 True or False
object Object Base type of all other types
string String A sequence of characters
decimal Decimal Precise fractional or integral type 128 (+ or -)1.0 x 10e-28 to 7.9 x 10e28
that can represent decimal
numbers with 29 significant digits
DateTime DateTime Represents date and time 0:00:00am 1/1/01 to 11:59:59pm
12/31/9999
Value Type:
A data type is a value type if it holds a data value within its own memory space. It means variables of
these data types directly contain their values.
Pass By Value :
When you pass a value type variable from one method to another method, the system creates a separate
copy of a variable in another method, so that if value got changed in the one method won't affect on the
variable in another method.
www.enosislearning.com
Page 17
Example : static void ChangeValue(int x) Output :
{
x = 200; 100
200
Console.WriteLine(x);
} 100
Console.WriteLine(i);
ChangeValue(i);
Console.WriteLine(i);
}
In the above example, variable i in Main() method remains unchanged even after we pass it
to the ChangeValue() method and change it's value there.
Reference Type :
Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where
the value is being stored. In other words, a reference type contains a pointer to another memory location
that holds the data.
For example, consider following string variable:
The following image shows how the system allocates the memory for the above string variable.
Pass By Reference :
When you pass a reference type variable from one method to another, it doesn't create a new copy;
instead, it passes the address of the variable. If we now change the value of the variable in a method, it
will also be reflected in the calling method.
Datatype conversions
1.Implicit Conversion
2. Explicit Conversion
Implicit Conversion
Implicit conversion is done by the compiler:
1. When there is no loss of information if the conversion is done
2. If there is no possibility of throwing exceptions during the conversion
Example: Converting an int to a float will not loose any data and no exception will be thrown, hence an
implicit conversion can be done.
Explicit Conversion
Where as when converting a float to an int, we loose the fractional part and also a possibility of overflow
exception. Hence, in this case an explicit conversion is required. For explicit conversion we can use cast
operator or the convert class in c#. Eplicit Conversion can be done using following ways :
1. Type cast
2. Convert Class
www.enosislearning.com
Page 19
3. Parse() Method
4. TryParse() Method
Parse() Method:
using System;
class Program
{
public static void Main()
{
string s = “Hello World”;
www.enosislearning.com
Page 21
Access Modifier Keywords:
Access modifiers are applied on the declaration of the class, method, properties, fields and other
members. They define the accessibility of the class and its members.
Access
Modifiers Usage
public The Public modifier allows any part of the program in the same assembly or another
assembly to access the type and its members.
private The Private modifier restricts other parts of the program from accessing the type
and its members. Only code in the same class or struct can access it.
internal The Internal modifier allows other program code in the same assembly to access the
type or its members. This is default access modifiers if no modifier is specified.
protected The Protected modifier allows codes in the same class or a class that derives from
that class to access the type or its members.
The following six accessibility levels can be specified using the access modifiers:
protected: Access is limited to the containing class or types derived from the containing class.
protected internal: Access is limited to the current assembly or types derived from the containing
class.
private protected: Access is limited to the containing class or types derived from the containing class
within the current assembly.
www.enosislearning.com
Page 22
Operators :
C# has rich set of built-in operators and provides the following type of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
Operator Description Example
Relational Operators
Operator Description Example
> Checks if the value of left operand is greater than the value of (A > B) is
right operand, if yes then condition becomes true. not true.
< Checks if the value of left operand is less than the value of (A < B) is
right operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is
the value of right operand, if yes then condition becomes true. not true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is
www.enosislearning.com
Page 23
value of right operand, if yes then condition becomes true. true.
Logical Operators
Operator Description Example
&& Called Logical AND operator. If both the operands are non zero (A && B) is
then condition becomes true. false.
! Called Logical NOT Operator. Use to reverses the logical state !(A && B) is
of its operand. If a condition is true then Logical NOT operator true.
will make false.
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as
follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; then in the binary format they are as follows −
A = 0011 1100
B = 0000 1101
-------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60 and
variable B holds 13, then −
Show Examples
www.enosislearning.com
Page 24
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12,
both operands. which is 0000
1100
^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) = 49,
but not both. which is 0011
0001
~ (~A ) = 61,
which is 1100
0011 in 2's
Binary Ones Complement Operator is unary and has the
complement
effect of 'flipping' bits.
due to a
signed binary
number.
<< Binary Left Shift Operator. The left operands value is moved A << 2 = 240,
left by the number of bits specified by the right operand. which is 1111
0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15,
right by the number of bits specified by the right operand. which is 0000
1111
Assignment Operators
Operator Description Example
www.enosislearning.com
Page 25
with the left operand and assign the result to left operand equivalent to C
=C*A
Miscellaneous Operators
Operator Description Example
www.enosislearning.com
Page 26
Decision Making
Decision making structures requires the programmer
to specify one or more conditions to be evaluated or
tested by the program, along with a statement or
statements to be executed if the condition is determined
to be true, and optionally, other statements to be executed
if the condition is determined to be false.
C# provides many decision making statements that
help the flow of the C# program based on certain logical
conditions. C# includes the following decision making
statements.
1. if statement
2. if-else statement
3. switch statement
4. Ternary operator :?
5. Switch case
if statement
The if statement contains boolean expression inside brackets followed by a single or multi line code block.
At runtime, if a boolean expression is evalutes to true then the code block will be executed.
Consider the following example where the if condition contains true as an expression.
if(true)
Example : {
Console.WriteLine("This will be displayed.");
}
if(false)
{
Console.WriteLine("This will not be displayed.");
}
if-else Statement
C# also provides for a second part to the if statement, that is else. The else statement must
follow if or else if statement. Also, else statement can appear only one time in a if-else statement chain.
Example :
int i = 10, j = 20;
if (i > j)
{
Console.WriteLine("i is greater than j");
}
else
{
www.enosislearning.com
Console.WriteLine("i is either equal to or less than j");
} Page 27
else if Statement
The 'if' statement can also follow an 'else' statement, if you want to check for another condition in the
else part.
int i = 10, j = 20;
Example : if (i > j)
{
Console.WriteLine("i is greater than j");
}
else if (i < j)
{
Console.WriteLine("i is less than j");
}
else
{
Console.WriteLine("i is equal to j");
}
Nested if Statements
Example : int i = 10;
if (i > 0)
{
if (i <= 100)
{
Console.WriteLine("i is positive number less than 100");
}
else
{
Console.WriteLine("i is positive number greater than 100");
}
}
Points to Remember :
1. 1. if-else statement controls the flow of program based on the evaluation of the
boolean expression.
2. 2. It should start from the if statement followed by else or else-if statements.
3. 3. Only one else statement is allowed in the if-else chain.
4. 4. Multiple else-if statements are allowed in a single if-else chain.
5. Nested if-else statement is allowed.
www.enosislearning.com
Page 28
Ternary operator ?:
The if-else statement can be replaced by ternary operator.
As you can see in the above syntax, ternary operator includes three parts. First part (before ?) includes
conditional expression that returns boolean value true or false. Second part (after ? and before :) contains
a statement which will be returned if the conditional expression in the first part evalutes to true. The third
part includes another statement which will be returned if the conditional expression returns false.
Example :
int x = 20, y = 10;
var result = x > y ? "x is greater than y" : "x is less than or equal to y";
Console.WriteLine(result);
Output:
x is greater than y
The ternary operator can return a value of any data type. So it is advisable to store it
in implicitly typed variable - var.
Example :
int x = 20, y = 10;
Console.WriteLine(result);
Output : 20
Switch Case
C# includes another decision making statement called switch. The switch statement executes the
code block depending upon the resulted value of an expression.
Switch statement contains an expression into brackets. It also includes multiple case labels, where
each case represents a particular literal value. The switch cases are seperated by a break keyword which
stops the execution of a particular case. Also, the switch can include a default case to execute if no case
value satisfies the expression.
int x = 10;
Example : Output :
switch (x)
{ Value of x is 10
case 5:
Console.WriteLine("Value of x is 5");
break;
case 10:
Console.WriteLine("Value of x is 10");
break;
case 15:
Console.WriteLine("Value of x is 15");
break;
default:
Console.WriteLine("Unknown value");
break;
}
Goto in switch:
The switch case can use goto to jump over a different case.
for loop
The for keyword indicates a loop in C#. The for loop executes a block of statements repeatedly until the
specified condition returns false.
for (variable initialization; condition; steps)
Syntax : {
//execute this code block as long as condition is satisfied
}
As per the syntax above, the for loop contains three parts: initialization, conditional expression and steps,
which are separated by a semicolon.
1. variable initialization: Declare & initialize a variable here which will be used in conditional
expression and steps part.
2. condition: The condition is a boolean expression which will return either true or false.
3. steps: The steps defines the incremental or decremental part
www.enosislearning.com
Page 31
while loop:
C# includes the while loop to execute a block of code repeatedly.
While(boolean expression)
Syntax: {
//execute code as long as condition returns true
}
As per the while loop syntax, the while loop includes a boolean expression as a condition which will return
true or false. It executes the code block, as long as the specified conditional expression returns true. Here,
the initialization should be done before the loop starts and increment or decrement steps should be
inside the loop.
int i = 0;
Example :
while (i < 10)
{
Console.WriteLine("Value of i: {0}", i);
i++;
}
Output : Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
while loop inclues an expression i < 10. Inside while loop, value of i increased to 1 (using i++). So, the
above while loop will be executed till the value of i will be 10.
Use the break keyword to exit from a while loop as shown below.
www.enosislearning.com
int i = 0;
Page 32
while (true)
{
Console.WriteLine("Value of i: {0}", i);
Example : Output :
Value of i: 0
do while
The do-while loop is the same as a 'while' loop except that the block of code will be executed at least
once, because it first executes the block of code and then it checks the condition.
Syntax : do
{
//execute code block
} while(boolean expression);
As per the syntax above, do-while loop starts with the 'do' keyword followed by a code block and boolean
expression with 'while'.
Example: int i = 0;
do
{
Console.WriteLine("Value of i: {0}", i);
i++;
Output :
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
www.enosislearning.com
Page 33
Array
“An array is a collection of similar data types.”
An array stores a fixed-size sequential collection of elements of the same type. An array is
used to store a collection of data, but it is often more useful to think of an array as a collection of
variables of the same type stored at contiguous memory locations.
Declaring Arrays
To declare an array in C#, you can use the following syntax −
datatype[] arrayName;
where,
datatype is used to specify the type of elements in the array.
[ ] specifies the rank of the array. The rank specifies the size of the array.
arrayName specifies the name of the array.
For example,
double[] balance;
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is initialized, you
can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array. For
example,
double[] balance = new double[10];
www.enosislearning.com
Page 34
You may also omit the size of the array, as shown −
int [] marks = new int[] { 39, 17, 9, 72, 25};
You can copy an array variable into another target array variable. In such case, both the target and
source point to the same memory location −
int [] marks = new int[] { 39, 17, 9, 72, 25};
int[] score = marks;
NOTE : An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array.
Multi-dimensional Array
C# also supports multi-dimensional arrays. A multi-dimensional array is a two dimensional series like rows
and columns. int[,] intArray = new int[3,2]{
{1, 2},
{3, 4},
{5, 6}
};
// or
int[,] intArray = { {1, 1}, {1, 2}, {1, 3} };
The values of a multi-dimensional array can be accessed using two indexes. The first index is for the row
and the second index is for the column. Both the indexes start from zero.
intArray[1,0]; // 3
intArray[1,1]; // 4
intArray[2,0]; // 5
intArray[2,1]; // 6
www.enosislearning.com
Page 35
Jagged Array
A jagged array is an array of an array. Jagged arrays store arrays instead of any other data
type value directly.
A jagged array is initialized with two square brackets [][]. The first bracket specifies the size
of an array and the second bracket specifies the dimension of the array which is going to be
stored as values. (Remember, jagged array always store an array.)
int[][] intJaggedArray = new int[2][];
Console.WriteLine(intJaggedArray[0][0]); // 1
Console.WriteLine(intJaggedArray[0][2]); // 3
Console.WriteLine(intJaggedArray[1][1]); // 5
www.enosislearning.com
Page 36
Methods
Methods are also called as functions. Methods make the maintenance of your application easier.
Methods are extremely useful because they allow you to define your logic once, and use it at many times.
Syntax :
[attributes]
Access-modifier Return-type Method-name (Parameter-list)
{
//Method-body
}
Calling Methods in C#
You can call a method using the name of the method.
Example :
Class Test {
public int compare(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
Value Parameter
Creates a copy of the parameter passed, so modifications does not affect each other.
Reference Parameter
The ref keyword on a method parameter causes a method to refer to the same variable that was passed into the
method. Any changes made to the parameter it the method will be reflected in that variable when control passes
back to the calling method.
Output Parameter
The out keyword is use when you want a method to return more than one value.
www.enosislearning.com
Page 38
Parameter Arrays
The params keyword lets you specify a method parameter that takes a variable number of arguments.
You can send a comma-seperated list of arguments, or an array, or no arguments. Params keyword should
be the last one in the parameter list in method declaration, and only one params keyword is permitted in
a method declaration.
Enum
In C#, enum is a value type data type. The enum is used to declare a list of named integer constants. It can
be defined using the enum keyword directly inside a namespace, class, or structure. The enum is used to
give a name to each constant so that the constant integer can be referred using its name.
By default, the first member of an enum has the value 0 and the value of each successive enum member
is increased by 1. For example, in the following enumeration, Monday is 0, Tuesday is 1, Wednesday is 2
and so forth.
Example :
enum WeekDays
{ Output:
Monday = 0,
Tuesday =1, Friday
Wednesday = 2, 4
Thursday = 3,
Friday = 4,
Saturday =5,
Sunday = 6
}
static void Main(String[] args)
{
Console.WriteLine(WeekDays.Friday);
Console.WriteLine((int)WeekDays.Friday);
}
A change in the value of the first enum member will automatically assign incremental values to the
other members sequentially. For example, changing the value of Monday to 10, will assign 11 to Tuesday,
12 to Wednesday, and so on.
The enum can includes named constants of numeric data type e.g. byte, sbyte, short, ushort, int,
uint, long, or ulong.
Enum is mainly used to make code more readable by giving related constants a meaningful name.
It also improves maintainability.
Enum methods:
Enum is an abstract class that includes static helper methods to work with enums.
Enum method Description
Format Converts the specified value of enum type to the specified string
format.
www.enosislearning.com
Page 39
Enum method Description
GetName Returns the name of the constant of the specified value of specified
enum.
GetValues Returns an array of the values of all the constants of specified enum.
object Parse(type, string) Converts the string representation of the name or numeric value of
one or more enumerated constants to an equivalent enumerated
object.
bool TryParse(string, out TEnum) Converts the string representation of the name or numeric value of
one or more enumerated constants to an equivalent enumerated
object. The return value indicates whether the conversion
succeeded.
Example :
enum WeekDays
Output :
{
Monday,
Tuesday, Friday
Wednesday, WeekDays constant names:
Thursday, Monday
Friday, Tuesday
Saturday,
Wednesday
Sunday
Thursday
}
Friday
Saturday
Console.WriteLine(Enum.GetName(typeof(WeekDays), 4));
Console.WriteLine("WeekDays constant names:"); Sunday
foreach (string str in Enum.GetNames(typeof(WeekDays))) Enum.TryParse():
Console.WriteLine(str); Tuesday
Console.WriteLine("Enum.TryParse():");
WeekDays wdEnum;
Enum.TryParse<WeekDays>("1", out wdEnum);
Console.WriteLine(wdEnum);
www.enosislearning.com
Page 40
Quite often we have situations where a class method takes as an argument a custom option. Let's say we have
some kind of file access class and there is a file open method that has a parameter that might be one of read-mode,
write-mode, read-write-mode, create-mode and append-mode. Now you might think of adding five static member
fields to your class for these modes. Wrong approach! Declare and use an enumeration which is a whole lot more
efficient and is better programming practice in my opinion.
Classes
The Class consists of data and behavior. Class data (Member Variables) is represented by its fields and
behavior (Member functions) is represented by its methods.
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.
If you want to create a complex custom data types, then we can make use of classes.
Classes are declared by using the keyword class followed by the class name and a set of class members
surrounded by curly braces.
Note −
Access specifiers specify the access rules for the members as well as the class
itself. If not mentioned, then the default access specifier for a class type
is internal. Default access for the members is private.
Data type specifies the type of variable, and return type specifies the data type of
the data the method returns, if any.
To access the class members, you use the dot (.) operator.
The dot operator links the name of an object with the name of a member.
Members of Class
So far, the only class members you've seen are Fields, Methods, Constructors, and Destructors. Here is a
complete list of the types of members you can have in your classes:
Constructors
Destructors
Fields
Methods
Properties
Indexers
Delegates
Events
www.enosislearning.com
Page 41
Nested Classes
Constructor
The purpose of class constructor is to initialize class fields. A class constructor is automatically called when
an instance of a class is created.
Constructors always have the same name as the class and do not have any return values.
Constructors are not mandatory. If you do not provide a constructor, a default parameter-less constructor
is automatically provided.
Constructors can be overloaded by the number and type of parameters.
Destructor
Destructors have the same name as the class with tilt (~) symbol in front of them.
They do not take any parameters and do not return a value.
Destructors are places where you could put code to release any resources your class was holding during
its lifetime. They are normally called when the C# garbage collector decides to clean your object from
memory.
Static Constructor
Static constructors are used to initialize static fields in the class.
Static constructors are declared using the keyword static in front of the constructor name.
Static constructor is called only once, no matter how many instances you create.
Static constructors are called before instance constructors.
public class Circle
Example : {
public int radius;
public static double pi;
// Static Constructor
public static Circle()
{
Console.WriteLine("Static Constructor invoked");
pi = 3.14;
}
// Constructor
public Circle(int r)
{
Console.WriteLine("Instance Constructor invoked");
radius = r;
}
// instance Method
public void area()
{
Console.WriteLine("Area of circle = {0}", pi * radius * radius);
}
www.enosislearning.com
} Page 43
// Program start class
class ExampleClass
{
public static void Main()
Copy Constructor
A parameterized constructor that contains a parameter of same class type is called as copy constructor.
Main purpose of copy constructor is to initialize new instance to the values of an existing instance.
class Test2
{
int A, B;
public Test2(int X, int Y)
{
A = X;
B = Y;
}
//Copy Constructor
public Test2(Test2 T)
{
A = T.A;
B = T.B;
}
public void Print()
{
Console.WriteLine("A = {0} \tB = {1}", A, B);
}
}
class CopyConstructor
{
static void Main()
{
Test2 T2 = n ew Test2(80, 90);
//Invoking copy constructor
Test2 T3 = new Test2(T2);
Test2 T3 = Test2(T2);
T2.Print();
T3.Print();
Console.Read();
}
}
www.enosislearning.com
Page 44
Private Constructor
You can also create a constructor as private. When a class contains at least one private
constructor, then it is not possible to create an instance for the class. Private constructor is
used to restrict the class from being instantiated when it contains every member as static.
Private constructor a constructor with "private" access modifier in a class.
A class with private constructor cannot be inherited.
We cannot create an object of the class which has private constructor.
A long with private constructor we can also have public constructor
(overloaded constructor).
To access the methods or properties in a class with private constructor we
need to assign methods or properties with "static" keyword.
Properties
Properties provide the opportunity to protect a field in a class by reading and writing to it through the
property. C# properties enable this type of protection while also letting you access the property just like it
was a field.
Accessing Class Fields with Properties
Public class Customer
{
Private int m_id = -1;
Public int ID
{
Get { Return m_id; }
Set {
m_id = value;
}
}
Private string m_name = string.Empty;
Public string Name
{
Get { Return m_name; }
Set {
m_name = value;
}
}
}
Public class CustomerManagerWithProperties
www.enosislearning.com
Page 45
{
Public static void Main()
{
Customer cust = new Customer();
cust.ID = 1;
cust.Name = "Amelio Rosales";
Console.WriteLine( "ID: {0}, Name: {1}", cust.ID, cust.Name);
}
}
There are also private fields named m_id and m_name; which ID and Name, respectively, encapsulate.
Each property has two accessors, get and set.
The accessor returns the value of a field. The set accessor sets the value of a field with the contents of
value, which is the value being assigned by calling code. The value shown in the accessor is a C# reserved
word.
This was a read/write property, but you can also create read-only properties, which you'll learn about
next.
www.enosislearning.com
Page 46
Public class Customer
{
Private int m_id = -1;
Private string m_name = string.Empty;
www.enosislearning.com
Page 47
Public int ID
{
set {
m_id = value;
}
}
Private string m_name = string.Empty;
Public string Name
{
set {
m_name = value;
}
}
Public void DisplayCustomerData()
{
Console.WriteLine("ID: {0}, Name: {1}", m_id, m_name);
}
}
Public class WriteOnlyCustomerManager
{
Public static void Main()
{
Customer cust = new Customer();
cust.ID = 1;
cust.Name = "Amelio Rosales";
cust.DisplayCustomerData();
Console.ReadKey();
}
}
This time, the getaccessor is removed from the ID and Name properties of the Customer class, shown in
Listing 10-1.
The setaccessors have been added, assigning value to the backing store fields, m_id and m_name.
www.enosislearning.com
Page 48
Public string Name { get; set; }
}
Public class AutoImplementedCustomerManager
{
Static void Main()
{
Customer cust = new Customer();
cust.ID = 1;
cust.Name = "Amelio Rosales";
Console.WriteLine( "ID: {0}, Name: {1}", cust.ID, cust.Name);
Console.ReadKey();
}
}
Notice how the get and setaccessors in Listing 10-5 do not have implementations. In an auto-
implemented property, the C# compiler creates the backing store field behind the scenes, giving the
same logic that exists with traditional properties, but saving you from having to use all of the syntax of
the traditional property. As you can see in the Main method, the usage of an auto-implemented property
is exactly the same as traditional properties, which you learned about in previous sections.
www.enosislearning.com
Page 49
Inheritence
Inheritance is a feature of object-oriented programming languages that allows you to define a base class
that provides specific functionality (data and behavior) and to define derived classes that either inherit or
override that functionality.
Inheritance is one of the fundamental attributes of object-oriented programming. It allows you to
define a child class that reuses (inherits), extends, or modifies the behavior of a parent class. The class
whose members are inherited is called the base class. The class that inherits the members of the base
class is called the derived class.
When you derive a class from a base class, the derived class will inherit all members of the base
class except constructors, though whether the derived class would be able to access those members
would depend upon the accessibility of those members in the base class. C# gives us polymorphism
through inheritance. Inheritance-based polymorphism allows us to define methods in a base class and
override them with derived class implementations.
Thus if you have a base class object that might be holding one of several derived class objects,
polymorphism when properly used allows you to call a method that will work differently according to the
type of derived class the object belongs to.
Now see how we derive another class from this base class.
www.enosislearning.com
Page 50
class Dog : Animal
{
public Dog()
{
Console.WriteLine("Dog constructor");
}
public new void Talk()
{
Console.WriteLine("Dog talk");
}
public override void Sing()
{
Console.WriteLine("Dog song");
}
};
Okay, that came out just as expected. Now try this code out.
www.enosislearning.com
Page 51
public Maths()
{
Console.WriteLine("maths is called");
}
public Maths(int n1,int n2)
{
this.n1 = n1;
this.n2 = n2;
//Console.WriteLine("maths is called");
}
public void add()
{
total = n1 + n2;
Console.WriteLine("add=" + total);
}
}
public class Calculator : Maths
{
protected new int n2;
public Calculator()
{
Console.WriteLine("calculator is called");
}
public Calculator(int nn1, int nn2) : base(nn1,nn2)
{
Console.WriteLine("parameterized calculator is called");
}
public void sub()
{
total = n1 - n2;
Console.WriteLine("sub=" + total);
}
}
public class Scientific : Calculator
{
public Scientific()
{
Console.WriteLine("Scientific is called");
}
www.enosislearning.com
Page 52
}
Interface
An interface looks like a class, but has no implementation. The only thing it contains are definitions of
events, indexers, methods and/or properties. The reason interfaces only provide definitions is because
they are inherited by classes and structs, which must provide an implementation for each interface
member defined.
Because interfaces must be implemented by derived classes and structs, they define a contract.
Notice that this method does not have an implementation (instructions between curly braces - {}), but
instead ends with a semi-colon, ";". This is because the interface only specifies the signature of methods
that an inheriting class or struct must implement.
www.enosislearning.com
Page 53
Now that this class inherits the IMyInterfaceinterface, it must implement its members. It does this by
implementing the MethodToImplement() method. Notice that this method implementation has the exact
same signature, parameters and method name, as defined in the IMyInterface interface. Interfaces may
also inherit other interfaces.
Interface IParentInterface
{
void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface
{
void MethodToImplement();
}
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
iImp.ParentInterfaceMethod();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
public void ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMethod() called.");
}
}
IMyInterface and the interface it inherits, IParentInterface. When one interface inherits another, any
implementing class or struct must implement every interface member in the entire inheritance chain.
www.enosislearning.com
Page 54
Abstract Class
An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
An example of an abstract class declaration is:
abstract class absClass
{
}
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not
have any implementation in the abstract class, but the same has to be provided in its derived class.
An example of an abstract method:
Also, note that an abstract class does not mean that it should contain abstract members. Even we can
have an abstract class only with non abstract members. For example:
www.enosislearning.com
Page 55
}
//A Child Class of absClass
class absDerived:absClass
{
[STAThread]
static void Main(string[] args)
{
//You can create an
//instance of the derived class
absDerived calculate = new absDerived();
int added = calculate.AddTwoNumbers(10,20);
int multiplied = calculate.MultiplyTwoNumbers(10,20);
Console.WriteLine(<span class='cpp-string'>"Added : {0},
Multiplied : {1}"</span>, added, multiplied);
}
//using override keyword,
//implementing the abstract method
//MultiplyTwoNumbers
public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1 * Num2;
}
}
}
The access modifier of the abstract method should be same in both the abstract class and its derived
class. If you declare an abstract method as protected, it should be protected in its derived class.
Otherwise, the compiler will raise an error.
An abstract method cannot have the modifier virtual. Because an abstract method is implicitly
virtual.//Incorrect : public abstract virtual int MultiplyTwoNumbers();
An abstract member cannot be static. public abstract static int MultiplyTwoNumbers();
www.enosislearning.com
Page 56
Abstract class vs. Interface :
An abstract class can have abstract members as well non abstract members. But in an interface all the members are
implicitly abstract and all the members of the interface must override to its derived class.
An example of interface:
interface iSampleInterface
{
//All methods are automaticall abstract
int AddNumbers(int Num1, int Num2);
int MultiplyNumbers(int Num1, int Num2);
}
Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have
protected parts, static methods, etc.
A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using
the old version.
An Interface can only inherit from another An abstract class can inherit from a class and
Interface. one or more interfaces.
www.enosislearning.com
Page 57
Struct
In C++ a struct is just about the same as a class for all purposes except in the default access modifier for
methods. In C# a struct are a pale puny version of a class. I am not sure why this was done so, but perhaps
they decided to have a clear distinction between structs and classes. Here are some of the drastic areas
where classes and structs differ in functionality.
structs are stack objects and however much you try you cannot create them on the heap
structs cannot inherit from other structs though they can derive from interfaces
You cannot declare a default constructor for a struct, your constructors must have parameters
The constructor is called only if you create your struct using new, if you simply declare the struct
just as in declaring a native type like int, you must explicitly set each member's value before
you can use the struct
struct Student : IGrade
{
public int maths;
public int english;
public int csharp;
//Output
150
Passed
Because we haven't used new, the constructor does not get called. Anyway you have to initialize all the
member fields. If you comment out the line that does the initialization you will get a compiler error :-Use
of unassigned local variable 's2'
Student s3 = new Student(90);
Console.WriteLine(s3.GetTot());
Console.WriteLine(s3.GetGrade());
//Output
270
Brilliant
This time we use our custom constructor that takes an int as argument.
www.enosislearning.com
Page 59
complex data type storage.
The struct can't be base type to the classes and also to the other structure.
The class can inherit another class, interface and it can be base class to another class.
The struct can only inherit the interfaces
The class can inherit the interfaces, abstract classes.
The struct can have only constructor.
The class can have the constructor and destructor.
The struct can instantiated without using the new keyword.
The new keyword should be used to create the object for the class
The struct can't have the default constructor
The class will have the default constructor
The struct is by default sealed class hence it will not allow to inherit. It can't use the abstract,
sealed, base keyword.
The class can be declared as abstract, sealed class
The struct can't use the protected or protected internal modifier.
The class can use all the access modifiers.
The struct can't initialize at the time of declaration.
The class can have the initializes fields.
Partial Classes
Partial classes span multiple files. How can you use the partial modifier on a C# class declaration? With
partial, you can physically separate a class into multiple files. This is often done by code generators.
Program that uses partial class: C#
class Program
{
static void Main()
{
A.A1();
A.A2();
}
}
Contents of file A1.cs: C#
partial class A
{
public static void A1()
{
Console.WriteLine("A1");
}
}
www.enosislearning.com
Page 60
Contents of file A2.cs: C#
partial class A
{
public static void A2()
{
Console.WriteLine("A2");
}
}
Output
A1
A2
Sealed Classes
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is
defined as a sealed class, the class cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the NotInheritable
keyword serves the purpose of sealed. If a class is derived from a sealed class then the compiler throws an
error. If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
The following class definition defines a sealed class in C#: // Sealed class
Sealed class SealedClass
{
}
I create a sealed class SealedClass and use it from Class1. If you run this code then it will work fine.
But if you try to derive a class from the SealedClass, you will get an error.
www.enosislearning.com
Page 61
Class Class1
{
Static void Main(string[] args)
{
SealedClass sealedCls = new SealedClass();
int total = sealedCls.Add(4, 5);
Console.WriteLine("Total = " + total.ToString());
}
}
// Sealed class
Sealed class SealedClass
{
Public int Add(int x, int y)
{
return x + y;
}
}
class X
{
protected virtual void F() { Console.WriteLine("X.F"); }
protected virtual void F2() { Console.WriteLine("X.F2"); }
}
class Y : X
{
sealed protected override void F() { Console.WriteLine("Y.F"); }
protected override void F2() { Console.WriteLine("X.F3"); }
}
class Z : Y
{
// Attempting to override F causes compiler error CS0239.
// protected override void F() { Console.WriteLine("C.F"); }
// Overriding F2 is allowed.
protected override void F2() { Console.WriteLine("Z.F2"); }
}
www.enosislearning.com
Page 62
Static Class
Static class is a specialized class that cannot have any objects.
Example#1 for Static Class in C#:
public static class staticClass
{
}
public class testStaticClass
{
public static void Main()
{
staticClassobj = new staticClass(); //ERROR
}
}
In this example, the class staticClass is a static class because it has the keyword static in its declaration.
Hence staticClass cannot be instantiated.
But inside Main method of testStaticClass, staticClass is instantiated with the object obj.
This is incorrect leading to error:
Static class cannot be instantiated. But when static class cannot be instantiated, how can its data and
members be accessed? The members of a static class belongs to the class itself and they can only be
accessed using the class name.
www.enosislearning.com
Page 63
public static class staticClass
{
static intstaticInteger;
public static void setStaticInteger(inttmpData)
{
staticInteger = tmpData;
}
public static intgetStaticInteger()
{
return staticInteger;
}
}
public class testStaticClass
{
public static void Main()
{
staticClass.setStaticInteger(5);
Console.WriteLine("staticInteger = "+ staticClass.getStaticInteger());
Console.ReadLine();
}
Output:
In this example, the members of staticClass are accessed using syntax as highlighted below:
staticClass.setStaticInteger(5);
Characteristics of Static Class in C#
Members of Static Class Can Only Be Static
Static Class Can Contain Only Static Constructor
Static class can contain only static constructors and not instance constructors.
The above code will work if the constructor includes the keyword static as shown below:
public static class staticClass
{
static staticClass()
{
Console.WriteLine("Inside Constructor..");
}
public static intstaticInteger;
}
public class testStaticClass
{
public static void Main()
{
staticClass.staticInteger = 10;
Console.WriteLine("staticInteger = " + staticClass.staticInteger);
Console.ReadLine();
}
}
Output:
In the above example, constructor of staticClass is marked with the keyword static.
This is legal. The static constructor will get invoked before any members of the static class get invoked.
This is proven from the above output.
www.enosislearning.com
Page 66
Encapsulation
Encapsulation means where we consider the related group properties, methods and other
members as a single unit. This is usually called a class. This specifies access levels for each properties,
methods and for members of the class. In C # you can manage encapsulation using access modifies.
Abstraction allows you to hide the implementation while encapsulation helps to provide different
levels of access to the members and methods.
In c#, Encapsulation is implemented using the access modifier keywords.
Encapsulation is a process of binding the data members and member functions into a single unit.
Encapsulation means hiding the internal details of an object, i.e. how an object does
something.
Encapsulation prevents clients from seeing its inside view, where the behaviour of the
abstraction is implemented.
Encapsulation is a technique used to protect the information in an object from the
other object.
Hide the data for security such as making the variables as private, and expose the
property to access the private data which would be public.
Polymorphism
It is ability to take more than one form. An operation may exhibit different behavior in different
situations.
Ex:- An addition operation involving two numeric values will produce sum and the same addition
operation will produce a string. If we pass parameter numeric value then method return sum(numeric
value) and if we pass parameter String then same method is return string value .this called
Polymorphism.
This means taking different forms i.e same operation can have different behavior’s. In a real world
example take the operation "move". A bird will "Fly" and a dog will "walk" but both moves. In
programming we can take overriding and overloading as examples for polymorphism.
Method overloading
Method will have same name but different argument passed. This is a compile time polymorphism.
Example
I have called the method "CalculateTotalPrice" with different arguments. Depending on the arguments
related function is called.
Class Billing
www.enosislearning.com
Page 67
{
public double TotalPrice = 0.0;
public double CalculateTotalPrice(double UnitPrice,int NumberOfItems)
{
TotalPrice = UnitPrice * NumberOfItems;
return TotalPrice;
}
public double CalculateTotalPrice(doubleUnitPrice, intNumberOfItems,double
Discount)
{
TotalPrice = (UnitPrice * NumberOfItems)-((UnitPrice * NumberOfItems * Discount) /
100);
return TotalPrice;
}
static void Main(string[] args)
{
string Unit_Price;
string Number_Of_Items;
string Discount_;
double Total_Price;
double Total_Price_Discount;
Billing B = newBilling();
Total_Price = B.CalculateTotalPrice(Convert.ToDouble(Unit_Price),
Convert.ToInt16(Number_Of_Items));
Total_Price_Discount = B.CalculateTotalPrice(Convert.ToDouble(Unit_Price),
Convert.ToInt16(Number_Of_Items), Convert.ToDouble(Discount_));
www.enosislearning.com
Page 68
}
}
}
Method Hiding
Why did the compiler in the second listing generate a warning? Because C# not only supports method
overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is
hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the
second listing is thus:
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}
class B : A
{
public new void Foo() { Console.WriteLine("B::Foo()"); }
}
class Test
{
static void Main(string[] args)
{
A a;
B b;
a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"
a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
It allows you to invoke methods of derived class through base class reference during runtime.
It has the ability for classes to provide different implementations of methods that are called
through the same name.
www.enosislearning.com
Page 69
Polymorphism is of two types:
Compile time polymorphism is method and operators overloading. It is also called early binding.
In method overloading method performs the different task at the different input parameters.
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.
Caution:Don't confused method overloading with method overriding, they are different, unrelated
concepts. But they sound similar.
Whereas Overriding means changing the functionality of a method without changing the signature. We
can override a function in base class by creating a similar function in derived class. This is done by using
virtual/overrides keywords.
Base class method has to be marked with virtual keyword and we can override it in derived class using
override keyword.
Derived class method will completely overrides base class method i.e. when we refer base class object
created by casting derived class object a method in derived class will be called.
Example:
// Base class
public classBaseClass
{
public virtual void Method1()
{
Console.Write("Base Class Method");
}
}
// Derived class
public class DerivedClass : BaseClass
{
www.enosislearning.com
Page 70
public override void Method1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
public class Sample
{
public void TestMethod()
{
// calling the overriden method
DerivedClass objDC = new DerivedClass();
objDC.Method1();
// calling the baesd class method
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}
Output : Derived Class Method
Derived Class Method
Differences Among Method Overriding, Method Hiding (new Keyword) and Method
Shadowing in C#
1. The "override" modifier extends the base class method, and the "new" modifier hides it.
2. The "virtual" keyword modifies a method, property, indexer, or event declared in the base class
and allows it to be overridden in the derived class.
3. The "override" keyword extends or modifies a virtual/abstract method, property, indexer, or event
of the base class into the derived class.
4. The "new" keyword is used to hide a method, property, indexer, or event of the base class into the
derived class.
5. If a method is not overriding the derived method then it is hiding it. A hiding method must be
declared using the new keyword.
6. Shadowing is another commonly used term for hiding. The C# specification only uses "hiding" but
either is acceptable. Shadowing is a VB concept.
What are the differences between method hiding and overriding in C#?
1. For hiding the base class method from derived class simply declare the derived class method with
the new keyword.
www.enosislearning.com
Page 71
Whereas in C#, for overriding the base class method in a derived class, you need to declare the
base class method as virtual and the derived class method as overriden.
2. If a method is simply hidden then the implementation to call is based on the compile-time type of
the argument "this".
Whereas if a method is overridden then the implementation to be called is based on the run-time
type of the argument "this".
What are the differences between method hiding and method shadowing?
www.enosislearning.com
Page 72
Abstraction
Abstraction in Object Oriented Concepts means hiding the implementation and shows only the
necessary features of the object. For example we can achieve abstraction by creating classes. Sometimes
we may not want to know what is inside the class.
Abstraction is a process of hiding the implementation details and displaying the essential features.
Abstraction is "To represent the essential feature without representing the background details."
Abstraction lets you focus on what the object does instead of how it does it.
Abstraction provides you a generalized view of your classes or object by providing relevant
information.
www.enosislearning.com
Page 73
Abstraction is the process of hiding the working style of an object, and showing the information of
an object in an understandable manner.
Abstraction is "To represent the essential feature without representing the back
ground details."
Abstraction lets you focus on what the object does instead of how it does it.
Abstraction provides you a generalized view of your classes or object by providing
relevant information.
Abstraction is the process of hiding the working style of an object, and showing the
information of an object in understandable manner.
Abstraction Encapsulation
1. Abstraction solves the problem in the 1. Encapsulation solves the problem in the
design level. implementation level.
2. Abstraction is used for hiding the unwanted 2. Encapsulation means hiding the code and
data and giving relevant data. data into a single unit to protect the data from
outside world.
3. Abstraction lets you focus on what the 3. Encapsulation means hiding the internal
object does instead of how it does it details or mechanics of how an object does
something.
4. Abstraction- Outer layout, used in terms of 4. Encapsulation- Inner layout, used in terms
design. of implementation.
For Example:- For Example:- Inner Implementation detail of a
Outer Look of a Mobile Phone, like it has a Mobile Phone, how keypad button and Display
display screen and keypad buttons to dial a Screen are connect with each other using
number. circuits.
Exception in C#
An exception is a unforeseen error that arises during the execution of a program. A C# exception
is a response to an exceptional circumstance that arises while a program is running, such as an attempt
to divide by zero.
There are two types of exceptions in .Net, exceptions generated by the executing program and
exceptions generated by the CLR. Exceptions provide a programming paradigm for detecting and reacting
to unexpected events. When an exception arises, the state of the program is saved, the normal flow is
interrupted and the control is passed to an exception handler (if such exists in the current context).
www.enosislearning.com
Page 74
C# includes built-in classes for every possible exception. All the exception classes are directly or
indirectly derived from the Exception class. There are two main classes for exceptions -
SystemException and ApplicationException. SystemException is a base class for all CLR generated errors
whereas ApplicationException serves as a base class for all application related exceptions, which you want
to raise on business rule violation.
class ExceptionsDemo
{
static void Main()
{
string fileName = "WrongTextFile.txt";
ReadFile(fileName);
}
www.enosislearning.com
Page 76
Delegate
A function can have one or more parameters of different data types, but what if you want to pass a
function itself as a parameter? How does C# handle the callback functions or event handler? The answer
is - delegate.
Syntax for delegate declaration is −
delegate <return type> <delegate-name> <parameter list>
A delegate is a type safe function pointer. That is, it holds a reference (pointer) to a function.
The signature of the delegate must match the signature of the function, the delegate points to, otherwise
you get a compiler error. This is the reason delegates are called as type safe function pointers.
A delegate is similar to a class. You can create an instance of it, and when you do so, you pass in the
function name as a parameter to the delegate constructor, and it is to this function the delegate will point
to. All the delegates are implicitly derived from System.Delegate class.
class Program
Example : {
public delegate void DelTest(int value);
www.enosislearning.com
Page 77
Multicast Delegate
The delegate can points to multiple methods. A delegate that points multiple methods is called a
multicast delegate. The "+" operator adds a function to the delegate object and the "-" operator removes
an existing function from a delegate object.
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. The following program demonstrates
multicasting of a delegate −
Example : Output :
public delegate void DelTest(int value);
Number : 1,00,000
static void Main(string[] args)
{ Hexadecimal : 186A0
DelTest Del = DispNumeric; Money : $ 1,00,000.00
Del += DispHexadecimal;
Del += DispMoney;
Del(100000);
}
public static void DispNumber(int num)
{
Console.WriteLine("Number : {0,-12:N0}",num);
}
public static void DispMoney(int money)
{
Console.WriteLine("Money : {0:C}", money);
}
public static void DispHexadecimal(int dec)
{
Console.WriteLine("Hexadecimal : {0:X}", dec);
}
Array of Delegates
Creating an array of delegates is very similar to declaring an array of any type. The following example has
a couple of static methods to perform specific math related operations. Then you use delegates to call
these methods.
namespace Delegates
{
public class Operation
{
public static void Add(int a, int b)
{
www.enosislearning.com
Page 78
Console.WriteLine("Addition={0}",a + b);
}
Public static void Multiple(int a, int b)
{
Console.WriteLine("Multiply={0}", a * b);
}
}
Class Program
{
delegate void DelOp(int x, int y);
Static void Main(string[] args)
{
// Delegate instantiation
DelOp[] obj =
{
new DelOp(Operation.Add),
new DelOp(Operation.Multiple)
};
for (int i = 0; i <obj.Length; i++)
{
obj[i](2, 5);
obj[i](8, 5);
obj[i](4, 6);
}
Console.ReadLine();
}
}
}
In this code, you instantiate an array of Delop delegates. Each element of the array is initialized to refer to
a different operation implemented by the operation class. Then, you loop through the array, apply each
operation to three different values. After compiling this code, the output will be as follows;
Anonymous Methods
Anonymous methods, as their name implies, are nameless methods. They prevent creation of separate
methods, especially when the functionality can be done without a new method creation. Anonymous
methods provide a cleaner and convenient approach while coding.
Define an anonymous method with the delegate keyword and a nameless function body. This code
assigns an anonymous method to the delegate. The anonymous method must not have a signature.
The signature and return type is inferred from the delegate type. For example if the delegate has
three parameters and return a double type, then the anonymous method would also have the same
signature.
www.enosislearning.com
Page 79
namespace Delegates
{
class Program
{
// Delegate Definition
delegate void operation();
Static void Main(string[] args)
{
// Delegate instantiation
operation obj = delegate
{
Console.WriteLine("Anonymous method");
};
obj();
Console.ReadLine();
}
}
}
The anonymous methods reduce the complexity of code, especially where there are several events
defined. With the anonymous method, the code does not perform faster. The compiler still defines
methods implicitly.
Event
Events enable a class or object to notify other classes or objects when something of interest occurs. The
class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the
event are called subscribers.
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.
An event is nothing but an encapsulated delegate. As we have learned in the previous section, a delegate
is a reference type data type.
www.enosislearning.com
Page 80
A publisher is an object that contains the definition of the event and the delegate. The event-delegate
association is also defined in this object. A publisher class object invokes the event and it is notified to
other objects.
A subscriber is an object that accepts the event and provides an event handler. The delegate in the
publisher class invokes the method (event handler) of the subscriber class.
www.enosislearning.com
Page 81
Console.WriteLine("Money: {0:C}", money);
}
public void PrintTemperature(int num)
{
if (beforePrintEvent != null)
beforePrintEvent();
Event Arguments
Events can also pass data as an argument to their subscribed handler. An event passes arguments to the
handler as per the delegate signature.
public class PrintHelper
{
public delegate void BeforePrint(string message);
public event BeforePrint beforePrintEvent;
www.enosislearning.com
Page 83
}
Now, the subscriber class should have an event handler that has a string parameter. Number class
has a printHelper_beforePrintEvent function with string parameter.
class Number
{
private PrintHelper _printHelper;
public Number(int val)
{
_value = val;
_printHelper = new PrintHelper();
//subscribe to beforePrintEvent event
_printHelper.beforePrintEvent += printHelper_beforePrintEvent;
}
//beforePrintevent handler
void printHelper_beforePrintEvent(string message)
{
Console.WriteLine("BeforePrintEvent fires from {0}",message);
}
www.enosislearning.com
Page 84
get { return _value; }
set { _value = value; }
}
Generics
Generics introduce to the .NET Framework the concept of type parameters, which make it possible to
design classes and methods that defer the specification of one or more types until the class or method is
declared and instantiated by client code. For example, 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.
Generics allow for designing a classes and methods whose types are specified only at the time of
declaration and instantiation. This enables development of universal classes and methods that help in
improving performance, productivity and type-safety.
Example : public class GenericList<T>
{
public void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int.
GenericList<int> list1 = new GenericList<int>();
list1.Add(1);
// Declare a list of type string.
GenericList<string> list2 = new GenericList<string>();
list2.Add("");
// Declare a list of type ExampleClass.
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
list3.Add(new ExampleClass());
}
}
www.enosislearning.com
Page 85
A generic method is a method that is declared with type parameters, as follows:
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
public static void TestSwap()
{
int a = 1;
int b = 2;
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
www.enosislearning.com
Page 86
Generic Type Parameters
In a generic type or method definition, a type parameters is a placeholder for a specific type that a client
specifies when they instantiate a variable of the generic type.
A generic class, such as GenericList<T> , cannot be used as-is because it is not really a type; it is more like
a blueprint for a type. To use GenericList<T>, client code must declare and instantiate a constructed type
by specifying a type argument inside the angle brackets. The type argument for this particular class can be
any type recognized by the compiler. Any number of constructed type instances can be created, each one
using a different type argument, as follows:
GenericList<float> list1 = new GenericList<float>();
GenericList<ExampleClass> list2 = new GenericList<ExampleClass>();
GenericList<ExampleStruct> list3 = new GenericList<ExampleStruct>();
In each of these instances of GenericList<T>, every occurrence of T in the class will be substituted at run
time with the type argument. By means of this substitution, we have created three separate type-safe
and efficient objects using a single class definition.
Constraint Description
where T : struct The type argument must be a value type. Any value type
except Nullable<T> can be specified. For more information about
nullable types, see Nullable types.
where T : class The type argument must be a reference type. This constraint applies
also to any class, interface, delegate, or array type.
where T : The type argument must not be a reference type and must not contain
unmanaged any reference type members at any level of nesting.
www.enosislearning.com
Page 87
Constraint Description
where T : new() The type argument must have a public parameterless constructor.
When used together with other constraints, the new() constraint must
be specified last.
where T :<base The type argument must be or derive from the specified base class.
class name>
where T : U The type argument supplied for T must be or derive from the argument
supplied for U.
Attribute
C# provides a mechanism for defining declarative tags, called attributes, which you can place on certain
entities in your source code to specify additional information. The information that attributes contain can
be retrieved at runtime through reflection. You can use predefined attributes, or you can define your own
custom attributes.
An attribute is a declarative tag that is used to convey information to runtime about the behaviors of
various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You
can add declarative information to a program by using an attribute. They can also provide a reusable
element that can be applied to a variety of targets.
www.enosislearning.com
Page 88
Name of the attribute and its values are specified within the square brackets, before the element to
which the attribute is applied. Positional parameters specify the essential information and the name
parameters specify the optional information.
In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits
from Attribute can be used as a sort of "tag" on other pieces of code.
Example :
[Obsolete("TestClass1 is obsolete. Use TestClass2 instead.")]
public class TestClass1
{
}
public class TestClass2
{
}
The .Net Framework provides two types of attributes: the pre-defined attributes and custom
built attributes.
Predefined Attributes
The .Net Framework provides three pre-defined attributes −
AttributeUsage
Conditional
Obsolete
AttributeUsage
The pre-defined attribute AttributeUsage describes how a custom attribute class can be used. It
specifies the types of items to which the attribute can be applied.
Syntax for specifying this attribute is as follows −
[AttributeUsage (
validon,
AllowMultiple = allowmultiple,
Inherited = inherited
)]
Where,
The parameter validon specifies the language elements on which the attribute can be placed. It is
a combination of the value of an enumerator AttributeTargets. The default value
is AttributeTargets.All.
The parameter allowmultiple (optional) provides value for the AllowMultiple property of this
attribute, a Boolean value. If this is true, the attribute is multiuse. The default is false (single-use).
The parameter inherited (optional) provides value for the Inheritedproperty of this attribute, a
Boolean value. If it is true, the attribute is inherited by derived classes. The default value is false
(not inherited).
[AttributeUsage(
AttributeTargets.Class |
www.enosislearning.com
AttributeTargets.Constructor |
Page 89
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
Example :
Conditional
This predefined attribute marks a conditional method whose execution depends on a specified
preprocessing identifier.
It causes conditional compilation of method calls, depending on the specified value such
as Debug or Trace. For example, it displays the values of the variables while debugging a code.
Syntax for specifying this attribute is as follows −
[Conditional(
conditionalSymbol
)]
For example,
#define DEBUG
using System;
using System.Diagnostics;
[Conditional("DEBUG")]
public static void Message(string msg)
{
Console.WriteLine(msg);
}
}
class Test {
static void function1() {
Myclass.Message("In Function 1.");
function2();
}
static void function2() {
Myclass.Message("In Function 2.");
}
public static void Main() {
Myclass.Message("In Main function.");
function1();
Console.ReadKey();
}
}
Outout : In Main function
In Function 1
In Function 2
www.enosislearning.com
Page 90
Obsolete
This predefined attribute marks a program entity that should not be used. It enables you to inform the
compiler to discard a particular target element. For example, when a new method is being used in a class
and if you still want to retain the old method in the class, you may mark it as obsolete by displaying a
message the new method should be used, instead of the old method.
[Obsolete (message)]
[Obsolete (message, iserror)]
Where,
The parameter message, is a string describing the reason why the item is obsolete and what to
use instead.
The parameter iserror, is a Boolean value. If its value is true, the compiler should treat the use of
the item as an error. Default value is false (compiler generates a warning).
Example :
public class MyClass {
www.enosislearning.com
Page 91
}
[Help(HelpText="This is a class")]
class Customer
{
private string _CustomerCode;
Reflection
Reflection objects are used for obtaining type information at runtime. The classes that give access to the
metadata of a running program are in the System.Reflection namespace.
Reflection provides objects (of type Type) that describe assemblies, modules and types. You can
use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the
type from an existing object and invoke its methods or access its fields and properties. If you are using
attributes in your code, reflection enables you to access them.
The System.Reflection namespace contains classes that allow you to obtain information about the
application and to dynamically add types, values, and objects to the application.
Reflection has the following applications −
www.enosislearning.com
Page 92
It allows view attribute information at runtime.
It allows examining various types in an assembly and instantiate these types.
It allows late binding to methods and properties
It allows creating new types at runtime and then performs some tasks using those types.
Using reflection you can view the attribute information. The MemberInfo object of the
System.Reflection class needs to be initialized for discovering the attributes associated with a class. To
do this, you define an object of the target class, as –
System.Reflection.MemberInfo info = typeof(MyClass);
Example:
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
public readonly string Url;
namespace AttributeAppl {
class Program {
static void Main(string[] args) {
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
www.enosislearning.com
Page 93
System.Console.WriteLine(attributes[i]);
}
Console.ReadKey();
}
}
}
When it is compiled and run, it displays the name of the custom attributes attached to the
class MyClass −
HelpAttribute
Collection
We have learned about an array in the previous section. C# also includes specialized classes that hold
many values or objects in a specific series, that are called 'collection'.
There are two types of collections available in C#: non-generic collections and generic collections. We will
learn about non-generic collections in this section.
Every collection class implements the IEnumerable interface so values from the collection can be
accessed using a foreach loop.
The System.Collections namespace includes following non-generic collections.
Non-generic
Collections Usage
ArrayList ArrayList stores objects of any type like an array. However, there is no need to
specify the size of the ArrayList like with an array as it grows automatically.
SortedList SortedList stores key and value pairs. It automatically arranges elements in
ascending order of key by default. C# includes both, generic and non-generic
SortedList collection.
Stack Stack stores the values in LIFO style (Last In First Out). It provides a Push()
method to add a value and Pop() & Peek() methods to retrieve values. C#
includes both, generic and non-generic Stack.
Queue Queue stores the values in FIFO style (First In First Out). It keeps the order in
which the values were added. It provides an Enqueue() method to add values
and a Dequeue() method to retrieve values from the collection. C# includes
generic and non-generic Queue.
Hashtable Hashtable stores key and value pairs. It retrieves the values by comparing the
hash value of the keys.
BitArray 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
www.enosislearning.com
Page 94
Non-generic
Collections Usage
off (0).
ArrayList
It is similar to an array, except that it grows automatically as you add items in it. Unlike an
array, you don't need to specify the size of ArrayList.
ArrayList myArryList = new ArrayList();
www.enosislearning.com
Page 95
Method Description
GetRange Returns specified number of elements from specified index from
ArrayList.
IndexOf Search specified element and returns zero based index if found.
Returns -1 if element not found.
ToArray Returns compitible array from an ArrayList.
SortedList
The SortedList collection stores key-value pairs in the ascending order of key by default. SortedList class
implements IDictionary & ICollection interfaces, so elements can be accessed both by key and index.
Stack
C# includes a special type of collection which stores elements in LIFO style(Last In First Out). C# includes a
generic and non-generic Stack. Here, you are going to learn about the non-generic stack.
www.enosislearning.com
Page 96
Stack allows null value and also duplicate values. It provides a Push() method to add a value and Pop() or
Peek() methods to retrieve values.
Queue
C# includes a Queue collection class in the System.Collection namespace. Queue stores the elements in
FIFO style (First In First Out), exactly opposite of the Stack collection. It contains the elements in the order
they were added.
Queue collection allows multiple null and duplicate values. Use the Enqueue() method to add values and
the Dequeue() method to retrieve the values from the Queue.
Hashtable
C# includes Hashtable collection in System.Collections namespace, which is similar to
generic Dictionary collection. The Hashtable collection stores key-value pairs. It optimizes lookups by
computing the hash code of each key and stores it in a different bucket internally and then matches the
hash code of the specified key at the time of accessing values.
www.enosislearning.com
Page 97
Propertis and Methods of Hashtable
Property Description
Count Gets the total count of key/value pairs in the Hashtable.
Item Gets or sets the value associated with the specified key.
Methods Usage
Add Adds an item with a key and value into the hashtable.
Remove Removes the item with the specified key from the hashtable.
Multithreading
Multithreading or free-threading is the ability of an operating system to concurrently run programs that
have been divided into subcomponents, or threads.
A thread is defined as the execution path of a program. Each thread defines a unique flow of control.
Threading Concepts in C#
An AppDomain is a runtime representation of a logical process within a physical process. And a thread is
the basic unit to which the OS allocates processor time. To start with, each AppDomain is started with a
www.enosislearning.com
Page 98
single thread. But it is capable of creating other threads from the single thread and from any created
thread as well.
The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends
when the thread is terminated or completes execution.
Following are the various states in the life cycle of a thread −
The Unstarted State − It is the situation when the instance of the thread is created but the Start
method is not called.
The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle.
The Not Runnable State − A thread is not executable, when
o Sleep method has been called
o Wait method has been called
o Blocked by I/O operations
The Dead State − It is the situation when the thread completes execution or is aborted.
1 CurrentContext
Gets the current context in which the thread is executing.
2 CurrentCulture
Gets or sets the culture for the current thread.
3 CurrentPrinciple
Gets or sets the thread's current principal (for role-based security).
4 CurrentThread
Gets the currently running thread.
5 CurrentUICulture
Gets or sets the current culture used by the Resource Manager to look up
culture-specific resources at run-time.
6 ExecutionContext
Gets an ExecutionContext object that contains information about the
various contexts of the current thread.
7 IsAlive
Gets a value indicating the execution status of the current thread.
8 IsBackground
www.enosislearning.com
Page 99
Gets or sets a value indicating whether or not a thread is a background
thread.
9 IsThreadPoolThread
Gets a value indicating whether or not a thread belongs to the managed
thread pool.
10 ManagedThreadId
Gets a unique identifier for the current managed thread.
11 Name
Gets or sets the name of the thread.
12 Priority
Gets or sets a value indicating the scheduling priority of a thread.
13 ThreadState
Gets a value containing the states of the current thread.
The following table shows some of the most commonly used methods of the Thread class −
Sr.No. Method & Description
www.enosislearning.com
Page 100
5 public static void BeginThreadAffinity()
Notifies a host that managed code is about to execute instructions
that depend on the identity of the current physical operating system
thread.
www.enosislearning.com
Page 101
Synchronizes memory access as follows: The processor executing the
current thread cannot reorder instructions in such a way that
memory accesses prior to the call to MemoryBarrier execute after
memory accesses that follow the call to MemoryBarrier.
www.enosislearning.com
Page 102
Defining and Calling threads
using System.Threading;
public class ServerClass
{
// The method that will be called when the thread is started.
public void Instance Method()
{
Console.WriteLine("You are in InstranceMethod.Running on Thread A”);
Console.WriteLine("Thread A Going to Sleep Zzzzzzzz”);
Thread.Sleep(5000);
Console.WriteLine("back in static method. Running on Thread B");
}
}
public class Simple
{
public static int Main(String[] args)
{
Console.WriteLine ("Thread Simple Sample");
ServerClass serverObject = new ServerClass();
// Create the thread object, passing in the
// serverObject.InstanceMethod method using a ThreadStart delegate.
Thread InstanceCaller = new Thread(new ThreadStart(serverObject.InstanceMethod));
www.enosislearning.com
Page 103
// Start the thread.
StaticCaller.Start();
Console.WriteLine("The Main () thread calls this " +
"after starting the new StaticCaller threads.");
return 0;
}
}
If the code in this example is compiled and executed, you would notice how processor time is allocated
between the two method calls. If not for threading, you would have to wait till the first method slept for
3000 secs for the next method to be called. Try disabling threading in the above code and notice how
they work. Nevertheless, execution time for both would be the same.
File Handling
In the .NET framework, the System.IO namespace is the region of the base class libraries devoted to file
based input and output services. Like any namespace, the System.IO namespace defines a set of classes,
interfaces, enumerations, structures and delegates. The following table outlines the core members of this
namespace:
Class Types Description
Directory/ DirectoryInfo These classes support the manipulation of the system directory
structure.
DriveInfo This class provides detailed information regarding the drives that a
given machine has.
FileStream This gets you random file access with data represented as a stream
of bytes.
File/FileInfo These sets of classes manipulate a computer's files.
Path It performs operations on System.String types that contain file or
directory path information in a platform-neutral manner.
BinaryReader/ BinaryWriter These classes allow you to store and retrieve primitive data types as
binary values.
StreamReader/StreamWriter Used to store textual information to a file.
StringReader/StringWriter These classes also work with textual information. However, the
underlying storage is a string buffer rather than a physical file.
BufferedStream This class provides temp storage for a stream of bytes that you can
commit to storage at a later time.
www.enosislearning.com
Page 104
DirectoryInfo Class
The DirectoryInfo class contains a set of members for the creation, deletion, moving and enumeration over
directories and subdirectories. Here, in the following code sample, display the information related to temp
directory.
The previous code produces the information related to the temp directory located in the D drive as in the
following:
Typically, we make the assumption that the path passed in the constructor of the DirectoryInfo class
physically exists. However, if you attempt to interact with a nonexistent directory then the CLR will
throw an exception. So, we need to create a directory first to handle the exceptions that occur as in the
following.
Directory Class
The Directory class provides nearly the same functionality as DirecotryInfo. The Directory class typically
www.enosislearning.com
Page 105
returns string data rather than strongly typed DirectoryInfo objects. The following sample deletes the
directory and subdirectory in the D drive.
Here, first the user interface asks the user to enter the path of the file that he wanted to display. Later
that path is passed to the File method ReadAllText() method that reads all the text integrated in the file
and displays it over the text box.
Besides reading a file, we can write some contents over an existing text file by the File class WriteAllTest()
method as in the following:
1. File.WriteAllText(@"d:\test.txt", textBox2.Text);
It takes a path to save the file and content input method medium such as a text box or any other control.
www.enosislearning.com
Page 106
Stream
The .NET provides many objects such as FileStream, StreamReader/Writer, BinaryReader/Writer to read
from and write data to a file. A stream basically represents a chunk of data flowing between a source and
a destination. Stream provides a common way to interact with a sequence of bytes regardless of what
kind of devices store or display the bytes. The following table provides common stream member
functions:
Methods Description
Enumeration Values
FileMode Create, Append, Open, CreateNew, Truncate, OpenOrCreate
FileAccess Read, Write, ReadWrite
FileShare Inheritable, Read, None, Write, ReadWrite
The FileStream can read or write only a single byte or an array of bytes. You will be required to encode
the System.String type into a corresponding byte array. The System.Text namespace defines a type
named encoding that provides members that encode and decode strings to an array of bytes. Once
encoded, the byte array is persisted to a file with the FileStream.Write() method. To read the bytes back
into memory, you must reset the internal position of the stream and call the ReadByte() method. Finally,
you display the raw byte array and the decoded string to the console.
www.enosislearning.com
Page 107
2. {
3. string msg = "first program";
4. byte[] byteArray = Encoding.Default.GetBytes(msg);
5. fs.Write(byteArray, 0, byteArray.Length);
6. fs.Position = 0;
7.
8. byte[] rFile = new byte[byteArray.Length];
9.
10. for (int i = 0; i < byteArray.Length; i++)
11. {
12. rFile[i] = (byte)fs.ReadByte();
13. Console.WriteLine(rFile[i]);
14. }
15.
16. Console.WriteLine(Encoding.Default.GetString(rFile));
17. }
The following sample first writes a number of data contents to a new champu.dat file using BinaryWriter.
Later, to read the data, the BinaryReader class employs a number of methods.
1. class Program
2. {
3. static void Main(string[] args)
www.enosislearning.com
Page 108
4. {
5. // writing
6. FileInfo fi = new FileInfo("champu.dat");
7. using (BinaryWriter bw = new BinaryWriter(fi.OpenWrite()))
8. {
9. int x = 007;
10. string str = "hello champu ,one day you will become doomkatu";
11.
12. bw.Write(x);
13. bw.Write(str);
14. }
15.
16. //Reading
17. FileInfo f = new FileInfo("champu.dat");
18. using (BinaryReader br = new BinaryReader(fi.OpenRead()))
19. {
20. Console.WriteLine(br.ReadInt32());
21. Console.WriteLine(br.ReadString());
22. }
23. Console.ReadLine();
24.
25. }
26. }
www.enosislearning.com
Page 109
14. Console.WriteLine(input);
15. }
16. }
17. }
18. }
www.enosislearning.com
Page 110
ADO.Net
C# Programming
www.enosislearning.com
courses@enosislearning.com
Introduction to ADO.Net
What is ADO.NET?
ADO.NET is not a different technology. In simple terms, you can think of ADO.NET, as a set of classes
(Framework), that can be used to interact with data sources like Databases and XML files. This data can,
then be consumed in any .NET application. ADO stands for Microsoft ActiveX Data Objects.
ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET
www.enosislearning.com
Page 111
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.
Sample ADO.NET code to connect to SQL Server Database and retrieve data. Notice that we are
using SQLConnection, SQLCommand and SQLDataReader classes . All the objects are prefixed with the
word SQL. All these classes are present in System.Data.SqlClient namespace. So, we can say that the .NET
data provider for SQL Server is System.Data.SqlClient.
SqlConnection con = new SqlConnection("data source=.; database=Sample; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("Select * from tblProduct", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
con.Close();
www.enosislearning.com
Page 112
Data Provider for ODBC - System.Data.Odbc
Please note that, depending on the provider, the following ADO.NET objects have a different prefix
1. Connection - SQLConnection, OracleConnection, OleDbConnection, OdbcConnection etc
2. Command - SQLCommand, OracleCommand, OleDbCommand, OdbcCommand etc
3. DataReader - SQLDataReader, OracleDataReader, OleDbDataReader, OdbcDataReader etc
4. DataAdapter - SQLDataAdapter, OracleDataAdapter, OleDbDataAdapter, OdbcDataAdapter etc
The DataSet object is not provider specific. Once we connect to a Database, execute command, and
retrieve data into .NET application. The data can then be stored in a DataSet and work independently of
the database.
SQLConnection in ADO.NET
The first thing that we will have to do, when working with databases is to create a connection object.
There are 2 ways to create an instance of SqlConnection class as shown below.
Create an instance of SqlConnection class using the constructor that takes ConnectionString parameter
The ConnectionString parameter is a string made up of Key/Value pairs that has the information
required to create a connection object.
www.enosislearning.com
Page 113
To create a connection object with windows authentication
string ConnectionString = "data source=.; database=SampleDB; integrated security=SSPI";
The "data source" is the name or IP Address of the SQL Server that we want to connect to. If you are
working with a local instance of sql server, you can just specify DOT(.). If the server is on a network, then
use Name or IP address.
Note: Connections should be opened as late as possible, and should be closed as early as possible.
protected void Page_Load(object sender, EventArgs e)
{
//Create the connection object
SqlConnection connection = new SqlConnection("data source=.;
database=Sample_Test_DB; integrated security=SSPI");;
try
{
// Pass the connection to the command object, so the command object knows on
which
// connection to execute the command
SqlCommand cmd = new SqlCommand("Select * from tblProductInventory",
connection);
// Open the connection. Otherwise you get a runtime error. An open connection is
// required to execute the command
connection.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
catch (Exception ex)
{
// Handle Exceptions, if any
}
www.enosislearning.com
Page 114
finally
{
// The finally block is guarenteed to execute even if there is an exception.
// This ensures connections are always properly closed.
connection.Close();
}
}
We can also use "using" statement to properly close the connection as shown below. We don't have to
explicitly call Close() method, when using is used. The connection will be automatically closed for us.
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection("data source=.;
database=Sample_Test_DB; integrated security=SSPI"))
{
SqlCommand cmd = new SqlCommand("Select * from tblProductInventory",
connection);
connection.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
Common Interview Question: What are the 2 uses of an using statement in C#?
1. To import a namespace. Example: using System;
2. To close connections properly as shown in the example above
Connection Strings in web.config configuration file
There are 2 issues with hard coding the connection strings in application code
1. For some reason, if we want to point our application to a different database server, we will have to
change the application code. If you change application code, the application requires a re-build and a re-
deployment which is a time waster.
2. All the pages that has the connection string hard coded needs to change. This adds to the maintenance
overhead and is also error prone.
In real time, we may point our applications from time to time, from Development database to
testing database to UAT database.
Because of these issues, the best practice is to store the connection in the configuration file, from
which all the pages can read and use it. This way we have only one place to change, and we don't have to
re-build and re-deploy our application. This saves a lot of time.
In an asp.net web application, the configuration strings can be stored in web.config file, as shown
below. Give a meaningful name to your connection string. Since we are working with sql server, the
provider name is System.Data.SqlClient.
www.enosislearning.com
Page 115
<connectionStrings>
<add name="DatabaseConnectionString"
connectionString="data source=.; database=Sample_Test_DB; Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
www.enosislearning.com
Page 116
SqlCommand in ado.net
SqlCommand class is used to prepare an SQL statement or StoredProcedure that we want to execute on a
SQL Server database. In this session, we will discuss about executing Transact-SQL statements on a SQL
Server.
The following are the most commonly used methods of the SqlCommand class.
ExecuteReader - Use when the T-SQL statement returns more than a single value. For example, if the
query returns rows of data.
ExecuteNonQuery - Use when you want to perform an Insert, Update or Delete operation
ExecuteScalar - Use when the query returns a single(scalar) value. For example, queries that return the
total number of rows in a table.
The sample code below, executes a T-SQL statement, that returns multiple rows of data
using ExecuteReader() method.
In the example below, we are using ExecuteScalar() method, as the T-SQL statement returns a single
value.
www.enosislearning.com
Page 117
{
//Create an instance of SqlCommand class, specifying the T-SQL command
//that we want to execute, and the connection object.
SqlCommand cmd = new SqlCommand("Select Count(Id) from tblProductInventory",
connection);
connection.Open();
//As the T-SQL statement that we want to execute return a single value,
//use ExecuteScalar() method of the command object.
//Since the return type of ExecuteScalar() is object, we are type casting to int datatype
int TotalRows = (int)cmd.ExecuteScalar();
Response.Write("Total Rows = " + TotalRows.ToString());
}
}
The following example performs an Insert, Update and Delete operations on a SQL server database
using the ExecuteNonQuery() method of the SqlCommand object.
//Set to CommandText to the update query. We are reusing the command object,
//instead of creating a new command object
cmd.CommandText = "update tblProductInventory set QuantityAvailable = 101 where Id = 101";
//use ExecuteNonQuery() method to execute the update statement on the database
rowsAffected = cmd.ExecuteNonQuery();
Response.Write("Updated Rows = " + rowsAffected.ToString() + "<br/>");
//Set to CommandText to the delete query. We are reusing the command object,
www.enosislearning.com
Page 118
//instead of creating a new command object
cmd.CommandText = "Delete from tblProductInventory where Id = 102";
//use ExecuteNonQuery() method to delete the row from the database
rowsAffected = cmd.ExecuteNonQuery();
Response.Write("Deleted Rows = " + rowsAffected.ToString() + "<br/>");
}
}
Sql injection
In this example, we are building the query dynamically by concatenating the strings that the user has
typed into the textbox. This is extremely dangerous, as it is vulnerable to SQL injection attacks.
protected void GetProductsButton_Click(object sender, EventArgs e)
{
string ConnectionString =
ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection("DatabaseConnectionString"))
{
//Build the query dynamically, by concatenating the text, that the user has
//typed into the ProductNameTextBox. This is a bad way of constructing
//queries. This line of code will open doors for sql injection attack
SqlCommand cmd = new SqlCommand("Select * from tblProductInventory where ProductName like '" +
ProductNameTextBox.Text + "%'", connection);
connection.Open();
ProductsGridView.DataSource = cmd.ExecuteReader();
ProductsGridView.DataBind();
}
}
To give you a flavour of that, just imagine what could happen if the user types the following into the
TextBox, and clicks Get Products button.
i'; Delete from tblProductInventory --
The entire data from tblProductInventory table is deleted. This is called SQL injection attack. I have
seen a lot of new developers building queries dynamically by concatenating the strings, that end users
enter into user interface controls like textboxes. Just imagine the extent of damage that can happen as a
result of sql injection.
However, sql injection can be easily avoided, by using parameterized queries or stored
procedures.
www.enosislearning.com
Page 119
Sql Injection prevention using “Parametrized Queries”
The above code can be easily re-written using parameterized queries to prevent sql injection attack. The
re-written code is shown below. Notice, that the query now uses parameter - @ProductName. The value
for this parameter is then provided using the AddWithValue() method. The parameter is associated with
the command object using Prameters collection property of the command object.
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
// Parameterized query. @ProductName is the parameter
string Command = "Select * from tblProductInventory where ProductName like @ProductName" ;
SqlCommand cmd = new SqlCommand(Command, con);
// Provide the value for the parameter
cmd.Parameters.AddWithValue("@ProductName", TextBox1.Text + "%");
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
www.enosislearning.com
Page 120
// The command, that we want to execute is a stored procedure,
// so specify the name of the procedure as cmdText
SqlCommand cmd = new SqlCommand("spGetProductsByName", con);
// Specify that the T-SQL command is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
// Associate the parameter and it's value with the command object
cmd.Parameters.AddWithValue("@ProductName", TextBox1.Text + "%");
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
Note: Please make sure to add the following using declarations at the top of the code behind page.
using System.Data.SqlClient;
using System.Configuration;
Now, run the application. Fill in the employee details and click Submit. The Employee row gets added to
the database, and the generated EmployeeId is shown on the screen.
You cannot create an instance of SqlDataReader using the new operator as shown below. If you try to
www.enosislearning.com
Page 122
new up SqlDataReader, you will get a compilation error stating - The type
'System.Data.SqlClient.SqlDataReader' has no constructors defined.
SqlDataReader rd = new SqlDataReader();
The SqlCommand object's ExecuteReader() method creates and returns an instance of SqlDataReader.
SqlCommand command = new SqlCommand("Select * from tblProductInventory", connection);
SqlDataReader reader = command.ExecuteReader();
Another important point to keep in mind is that, SqlDataReader is connection oriented and the
connection needs to be opened explicitly, by calling the Open() method on the connection object, before
calling the ExecuteReader() method of the command object.
string ConnectionString
= ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(ConnectionString))
www.enosislearning.com
Page 123
{
connection.Open();
SqlCommand command = new SqlCommand("Select * from tblProductInventory",connection);
using (SqlDataReader reader = command.ExecuteReader())
{
// Create the DataTable and columns. This will
// be used as the datasource for the GridView
DataTable sourceTable = new DataTable();
sourceTable.Columns.Add("ID");
sourceTable.Columns.Add("Name");
sourceTable.Columns.Add("Price");
sourceTable.Columns.Add("DiscountedPrice");
while (reader.Read())
{
//Calculate the 10% discounted price
int OriginalPrice = Convert.ToInt32(reader["UnitPrice"]);
double DiscountedPrice = OriginalPrice * 0.9;
www.enosislearning.com
Page 124
To retrieve the second result-set from SqlDataReader object, use the NextResult() as shown in the code
snippet below. The NextResult() method returns true and advances to the next result-set.
string ConnectionString
= ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("select * from tblProductInventory; select * from
tblProductCategories", connection);
using (SqlDataReader reader = command.ExecuteReader())
{
ProductsGridView.DataSource = reader;
ProductsGridView.DataBind();
while (reader.NextResult())
{
CategoriesGridView.DataSource = reader;
CategoriesGridView.DataBind();
}
}
}
The SqlDataReader object's Read() method is used to loop thru the rows in a given result set,
where as the NextResult() method is used to loop thru multiple result sets.
SqlDataAdapter in ADO.NET
SqlDataReader is connection oriented, meaning it requires an active and open connection to the data
source. SqlDataAdapter and DataSet provides us with disconnected data access model
string ConnectionString
= ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
// Create an instance of SqlDataAdapter. Spcify the command and the connection
SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from tblProductInventory", connection);
// Create an instance of DataSet, which is an in-memory datastore for storing tables
DataSet dataset = new DataSet();
// Call the Fill() methods, which automatically opens the connection, executes the command
// and fills the dataset with data, and finally closes the connection.
dataAdapter.Fill(dataset);
GridView1.DataSource = dataset;
GridView1.DataBind();
}
If you want to execute stored procedure spGetProductInventory, using the SqlDataAdapter, just specify
the name of the procedure instead of the in-line sql statement.
www.enosislearning.com
Page 126
To execute stored procedure spGetProductInventoryById, we need to associate
parameter @ProductId to the SqlDataAdapeter object's SelectCommand as shown below.
string ConnectionString
= ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
// Create an instance of SqlDataAdapter, specifying the stored procedure
// and the connection object to use
SqlDataAdapter dataAdapter = new SqlDataAdapter("spGetProductInventoryById", connection);
// Specify the command type is an SP
dataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
// Associate the parameter with the stored procedure
dataAdapter.SelectCommand.Parameters.AddWithValue("@ProductId", 1);
DataSet dataset = new DataSet();
dataAdapter.Fill(dataset);
GridView1.DataSource = dataset;
GridView1.DataBind();
}
DataSet in ADO.Net
When the following stored procedure is executed, we get 2 result-sets
Create procedure spGetProductAndCategoriesData
as
Begin
Select ProductId, ProductName, UnitPrice
from tblProductInventory
Drag and drop 2 GridView controls onto the webform and change the ID
to GridViewProducts and GridViewCategories. The HTML in the aspx page should be as shown below.
<asp:GridView ID="GridViewProducts" runat="server">
</asp:GridView>
<br />
<asp:GridView ID="GridViewCategories" runat="server">
</asp:GridView>
www.enosislearning.com
Page 127
To specify the specific DataTable, that you want to bind to a gridview control, use the Tables collection
property of the dataset object, as shown below.
string ConnectionString
= ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter("spGetProductAndCategoriesData", connection);
dataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet dataset = new DataSet();
dataAdapter.Fill(dataset);
GridViewProducts.DataSource = dataset.Tables[0];
GridViewProducts.DataBind();
GridViewCategories.DataSource = dataset.Tables[1];
GridViewCategories.DataBind();
}
By default the tables in the DataSet will have table names as Table, Table1, Table2etc. So if you want to
give the tables in the DataSet a meaningful name, use the TableName property as shown below.
dataset.Tables[0].TableName = "Products";
dataset.Tables[1].TableName = "Categories";
These table names can then be used when binding to a GridView control, instead of using the integral
indexer, which makes your code more readable, and maintainable.
GridViewProducts.DataSource = dataset.Tables["Products"];
GridViewProducts.DataBind();
GridViewCategories.DataSource = dataset.Tables["Categories"];
GridViewCategories.DataBind();
command.Connection = excelConnection;
command.CommandText = "INSERT INTO [Sheet1$](ID ,Name )
VALUES(10,'Kapil')";
command.ExecuteNonQuery();
excelConnection.Close();
string connectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=D:\Customers.xlsx;Extended Properties=""Excel
12.0;HDR=YES;""";
// if you don't want to show the header row (first row)
in the grid // use 'HDR=NO' in the string
dataAdapter.Fill(dTable);
ReadData(dTable);
www.enosislearning.com
Page 129
//dTable.Dispose()
dataAdapter.Dispose();
dbCommand.Dispose();
excelConnection.Close();
excelConnection.Dispose();
www.enosislearning.com
Page 130
Convert XML to Dataset
Examples
ds.ReadXml(@"E:\1.ENOSISLEARNING\1.0
NetBasics\Files\OutputCustomer.xml");
int i = 0;
for (int r = 0; r <= ds.Tables[0].Rows.Count - 1; r++)
{
int id =
Convert.ToInt32(ds.Tables[0].Rows[r][0].ToString());
string name = ds.Tables[0].Rows[r][1].ToString();
DateTime enqdate =
Convert.ToDateTime(ds.Tables[0].Rows[r][2]);
//MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[2].ToString());
}
www.enosislearning.com
Page 131
SqlCommandBuilder
SqlCommandBuilder automatically generates INSERT, UPDATE and DELETE sql statements based on the
SELECT statement for a single table.
For the Transact-SQL statements to be generated using SqlCommandBuilder, there are 2 steps
Step 1. Set the "SelectCommand" property of the SqlDataAdapter object
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT_Query", con);
Step 2. Create an instance of SqlCommandBuilder class and associate the SqlDataAdapter object created
above using DataAdapter property of the SqlCommandBuilder object
SqlCommandBuilder builder = new SqlCommandBuilder();
builder.DataAdapter = dataAdapter;
Please Note: Step 2, can also be done in single line as shown below. Here, we are passing the
SqlDataAdapter instance as an argument to SqlCommandBuilder class constructor
SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);
www.enosislearning.com
Page 132
string selectQuery = "Select * from tblStudents where ID = " +
txtStudentID.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(selectQuery, connection);
// Store DataSet and the select query in ViewState, so they can be used
// later to generate the T-SQL commands using SqlCommandBuilder class
ViewState["DATASET"] = dataSet;
ViewState["SELECT_QUERY"] = selectQuery;
if (dataSet.Tables["Students"].Rows.Count > 0)
{
DataRow dataRow = dataSet.Tables["Students"].Rows[0];
txtStudentName.Text = dataRow["Name"].ToString();
txtTotalMarks.Text = dataRow["TotalMarks"].ToString();
ddlGender.SelectedValue = dataRow["Gender"].ToString();
lblStatus.Text = "";
}
else
{
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Text = "No record with ID = " + txtStudentID.Text;
}
}
DataSet ds = (DataSet)ViewState["DATASET"];
DataRow dr = ds.Tables["Students"].Rows[0];
dr["Name"] = txtStudentName.Text;
dr["Gender"] = ddlGender.SelectedValue;
dr["TotalMarks"] = txtTotalMarks.Text;
dr["Id"] = txtStudentID.Text;
www.enosislearning.com
Page 134