[go: up one dir, main page]

100% found this document useful (1 vote)
137 views210 pages

LECTUR#01 Visualprogramming31-10-2006

Here are the answers to the quiz questions in 3 lines or less each: 1. Attributes of variables include scope, type, lifetime, accessibility. 2. .Net architecture includes CLR, assemblies, class libraries, applications. 3. Static libraries are linked during compile time, dynamic libraries are linked during runtime. 4. Interfaces define contracts without implementation, used for polymorphism. 5. Delegate is a type-safe reference to a method with a signature. 6. Static variables shared across instances, instance variables unique to each instance. 7. Message is data sent between objects/components during communication.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
137 views210 pages

LECTUR#01 Visualprogramming31-10-2006

Here are the answers to the quiz questions in 3 lines or less each: 1. Attributes of variables include scope, type, lifetime, accessibility. 2. .Net architecture includes CLR, assemblies, class libraries, applications. 3. Static libraries are linked during compile time, dynamic libraries are linked during runtime. 4. Interfaces define contracts without implementation, used for polymorphism. 5. Delegate is a type-safe reference to a method with a signature. 6. Static variables shared across instances, instance variables unique to each instance. 7. Message is data sent between objects/components during communication.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 210

Kohat University of Science and Technology

C# . Net
Spring 2006
Visual Programming
Lecture 02-03-04-05-06-07-08-09:
using C#

Oct 10-2006-Nov 07-2006

Amjad Mehmood
Lec.IIT 1
.NET Framework and the
Common Language Runtime
• .NET Framework
– Heart of .NET strategy
» Manages and executes applications and Web services
» Provides security, memory management and other programming
capabilities
– Includes Framework class library (FCL)
» Pre-packaged classes ready for reuse
» Used by any .NET language
– Details contained in Common Language Specification
(CLS)
» Submitted to European Computer Manufacturers Association to
make the framework easily converted to other platforms
– Executes programs by Common Language Runtime (CLR)
Amjad Mehmood
Lec.IIT 2
.NET Framework and the
Common Language Runtime (II)
• Common Language Runtime (CLR)
– Central part of framework
» Executes Visual Basic .NET programs
– Compilation process
» Two compilations take place
» Programs compiled to Microsoft Intermediate Language
(MSIL)

Defines instructions for CLR


» MSIL code translated into machine code

Machine code for a


particular platform

Amjad Mehmood
Lec.IIT 3
.NET Framework and the
Common Language Runtime (III)
• Why two compilations?
– Platform independence
» .NET Framework can be installed on different platforms
» Execute .NET programs without any modifications to code
– Language independence
» .NET programs not tied to particular language
» Programs may consist of several .NET-compliant languages
» Old and new components can be integrated

• Other advantages of CLR


– Execution-management features
» Manages memory, security and other features
» Relieves programmer of many responsibilities
» More concentration on program logic

Amjad Mehmood
Lec.IIT 4
The Microsoft .Net Framework Architecture

Micosoft.Net Famework

Application Programming Model

ASP.NET Win Form

Class Lib,Data,debug tool etc

CLR,Assemblies,Security
Amjad Mehmood
Lec.IIT 5
The .NET Framework class library

Amjad Mehmood
Lec.IIT 6
The JIT process and verification.
• When code is JIT compiled, the common language runtime checks
to make sure that the IL is correct.
• Rules common language runtime uses for verification are
• Common Language Specification (CLS)
• Common Type System (CTS).

Amjad Mehmood
Lec.IIT 7
Namespaces
• Logical grouping rather than physical groupings
• namespace Wrox
• {
• namespace ProCSharp
• {
• namespace Basics
• {
• class namespaceExample
• {
• // Code for the class here...
• }}}}
Amjad Mehmood
Lec.IIT 8
Namespaces Cont…

• We can use this syntax to organize the namespaces in our


namespace definitions too, so the code above could also be
written:
• namespace Wrox.ProCSharp.Basics
• {
• class NamespaceExample
• {
• // Code for the class here...
• }
• }

Amjad Mehmood
Lec.IIT 9
The using Statement
• say classes called NamespaceExample exist both in the
Wrox.ProCSharp.Basics and Wrox.ProCSharp.OOP namespaces. If we
then create a class called Test in the Wrox.ProCSharp namespace, and
instantiate one of the NamespaceExample classes in this class, we need to
specify which of these two classes we're talking about:
• using Wrox.ProCSharp;
• class Test
• {
• public static int Main()
• {
• Basics.NamespaceExample NSEx = new
Basics.NamespaceExample();
• return 0;
• }
• }

• CTS types contained within this namespace, as is much of .NET's core


functionality, such as console I/O.
Amjad Mehmood
Lec.IIT 10
Namespace Aliases
• Two or more name of the same namespace
• using alias = NamespaceName;
• using System;
• using Introduction = Wrox.ProCSharp.Basics;
• class Test
• {
• public static int Main()
• {
• Introduction.NamespaceExample NSEx = new
Introduction.NamespaceExample();
Console.WriteLine(NSEx.GetNamespace());
• return 0;
• }
• }

Amjad Mehmood
Lec.IIT 11
Console I/O
• Console.Write() - Writes the specified value to the console window
• Console.WriteLine() - Which does the same, but adds a new line character
at the end of the output.
• Example
• The following code lets the user input a line of text, and displays the first
character:
• int x = Console.Read();
• Console.WriteLine((char)x); This is similar, but returns the entire line of
text as a string:
• The following code lets the user input a line of text, and displays the first
character:
• string s = Console.ReadLine();
• Console.WriteLine(s);

Amjad Mehmood
Lec.IIT 12
Console I/O Cont…
• int i = 940;
• int j = 73;
• Console.WriteLine(" {0,4}\n+{1,4}\n ----\n {2,4}", i, j, i + j);
The result of this is:
• 940 + 73 ---- 1013
• StringDescription
• C Local currency format
• .D Decimal format. Converts an integer to base 10, and pads with leading zeros if a precision
specifier is given.
• E Scientific (exponential) format. The precision specifier sets the number of decimal places (6 by
default). The case of the format string (e or E) determines the case of the exponential symbol.
• F Fixed-point format; the precision specifier controls the number of decimal places. Zero is
acceptable.G General format. Uses E or F formatting, depending on which is the most compact.
• N Number format. Formats the number with commas as thousands separators, for example
32,767.44
• P Percent format.
• X Hexadecimal format. The precision specifier can be used to pad with leading zeros

Amjad Mehmood
Lec.IIT 13
• int i = 940;
• int j = 73;
• Console.WriteLine(" {0,4}\n+{1,4}\n ----\n {2,4}", i, j, i + j);
• The result of this is:
• 940
• + 73
----
1013
Example :02
• decimal i = 940.23m;
• decimal j = 73.7m;
• Console.WriteLine(" {0,9:C2}\n+{1,9:C2}\n ---------\n {2,9:C2}", i, j, i + j);
• The output of this in the United States is:
• $940.23
• + $73.70
• ---------
• $1,013.93
Amjad Mehmood
Lec.IIT 14
Our First C# Program

• using System;
• namespace Wrox.ProCSharp.Basics
• {
• class MyFirstCSharpClass
• {
• static void Main()
• {
• Console.WriteLine("This isn't at all like Java!");
• return;
• }
• }
• }

Amjad Mehmood
Lec.IIT 15
Execution Environment

• [C#/IL/CLR] [Java/Byte-Code/JVM]

Source MSIL
.Net Compiler
Code

Running
CLR
Program

Amjad Mehmood
Lec.IIT 16
MSIL

• Microsoft intermediate language


• CPU-independent language
• Set of instruction that can be effectively converted in
to native code
• Includes the instructions for
• loading, storing, initializing, and calling methods on
objects, arithmetic and logical operations ,control
flow, directly memory access and exception
handling.
• Can be converted to native code by JIT Compilation

Amjad Mehmood
Lec.IIT 17
JIT Compilation

• Converts MSIL to native code


• CPU-specific code that runs on the same computer
architecture that the JIT compiler is running on.

Amjad Mehmood
Lec.IIT 18
Quiz# 01
Time Allowed:10 Minutes
Marks:10

Note Please don’t write more than three lines

• What are the attributes of variable?


• Draw the diagram of .Net architecture
• What is difference between static and Dynamic libraries?
• Need and Use of interface?
• What is delegate?
• Difference between static and instance variable?
• What is Message?

Amjad Mehmood
Lec.IIT 19
using System;
namespace Shape
{
class cone
{
float height, radius ;
public cone ( float h, float r )
{
height = h ;
radius = r ;
}
public void displaydata( )
{
Console.WriteLine ( "Height = " + height ) ;
Console.WriteLine ( "Radius = " + radius ) ;
}
public void volume( )
{
float v ;
v = ( 1 / 3.0f ) * 3.14f * radius * radius * height ;
Console.WriteLine ( "\nVolume = " + v ) ;
} Amjad Mehmood
} Lec.IIT 20
class Class1
{
static void Main ( string [ ] args )
{
cone c1 = new cone ( 10.0f, 3.5f ) ;
cone c2 = new cone ( 20.0f, 6.2f ) ;

c1.displaydata( ) ;
c1.volume( ) ;

c2.displaydata( ) ;
c2.volume( ) ;
}
}
}

Amjad Mehmood
Lec.IIT 21
using System;
namespace StaticDemo
{
class sample
{
private static int count ;

public sample( )
{
count++ ;
}

public static void showcount( )


{
Console.WriteLine ( "Value of Count is: " + count ) ;
}
}

Amjad Mehmood
Lec.IIT 22
class Class1
{
static void Main ( string [ ] args )
{
sample s1 = new sample( ) ;
sample.showcount( ) ;

sample s2 = new sample( ) ;


sample.showcount( ) ;
}
}
}

Amjad Mehmood
Lec.IIT 23
using System;
namespace StaticDemo
{
class sample
{
public static int y;
public static int m ;
public static int d ;

static sample( )
{
DateTime dt = DateTime.Now ;
y = dt.Year ;
m = dt.Month ;
d = dt.Day ;
}

public static void showdate( )


{
Console.WriteLine ( "Year: " + y + " Month: " + m
+ " Day: " + d ) ;
}
} Amjad Mehmood
Lec.IIT 24
• class Class1
• {
• static void Main ( string [ ] args )
• {
• sample.showdate( ) ;
• }
• }
• }

Amjad Mehmood
Lec.IIT 25
Scope clashes for local variable
• using System;
• namespace Wrox.ProCSharp.Basics
• {
• public class ScopeTest
• {
• public static int Main()
• {
• for (int i = 0; i < 10; i++)
• {
• Console.WriteLine(i); } // i goes out of scope here We can declare a variable named
i again, because // there's no other variable with that name in scope
• for (int i = 9; i >= 0; i--)
• {
• Console.WriteLine(i);
• } // i goes out of scope here
• return 0;
• }
• }
• }
Amjad Mehmood
Lec.IIT 26
If we try to compile this, we'll get an error:

• public static int Main()


• {
• int j = 20;
• for (int i = 0; i < 10; i++)
• {
• int j = 30; // Can't do this - j is still in scope
• Console.WriteLine(j + i);
• }
• return 0;
• }

Amjad Mehmood
Lec.IIT 27
Scope clashes Cont…
• using System;
• namespace Wrox.ProCSharp.Basics
• {
• class ScopeTest2
• {
• static int j = 20;
• public static void Main()
• {
• int j = 30;
• Console.WriteLine(j);
• return;
• }
• }
• }
• C# makes a fundamental distinction between variables that are declared at
the type level (fields), and variables declared within methods (local
variables): Main() method hides the class-level variable with the same name, so when we
run this code, the number 30 will be displayed.

Amjad Mehmood
Lec.IIT 28
Scope clashes Cont…
• ...
• public static void Main()
• {
• int j = 30;
• Console.WriteLine(ScopeTest2.j);
• }
• ...

Amjad Mehmood
Lec.IIT 29
Constants

• const int a = 100; // This value cannot be changed


• once a value has been assigned, it can never be
overwritten.
• value of a constant must be computable at
compiletime
• Constants make it easier to avoid mistakes in your
programs.

Amjad Mehmood
Lec.IIT 30
Predefined Data Types
• Value Types
• Stores the value directly
• stored in different places in memory; value types in an area known as the
stack
• Int, char, double
• Reference Types
• Stores a reference to the value.
• Reference types are stored in an area known as the managed heap
• Class
• Interface
• Delegates
• Object
• String

Amjad Mehmood
Lec.IIT 31
Predefined Data Types Cont…
• The basic predefined types recognized by C# are not intrinsic (native) to the language but part
of the .NET Framework
• Name CTS Type Description Range (min:max)
• sbyte System.SByte 8-bit signed integer -128:127 (-27:27-1)
• short System.Int16 16-bit signed integer -32,768:32,767 (-215:215-1)
• int System.Int32 32-bit signed integer -2,147,483,648:2,147,483,647 (-231:231-1)

• long System.Int64 64-bit signed integer -9,223,372,036,854,775,808:


• float System.Single 32-bit single-precision floating- point 7±1.5 × 10-45 to ±3.4 × 1038
double System.Double 64-bit double-precision floating- point 15/16±5.0 × 10-324 to ±1.7 × 10308

• decimal System.Decimal 128-bit high precision decimal notation 28±1.0 × 10-28 to ±7.9 × 1028
• bool System.Boolean true or false

Amjad Mehmood
Lec.IIT 32
Diagram description

Amjad Mehmood
Lec.IIT 33
Examples of Val and Ref Type

• using System;
• namespace cSharp_ValueReference
• {
• class Class1
• {
• static public int x;
• [STAThread]
• static void Main(string[] args)
• {
• x=4; int y; y = x; x=0; //
• Console.WriteLine(x);
• Console.WriteLine(y);
• Class2 Class2 ref1 = new Class2();
Amjad Mehmood
• ref1.refValue=5; Lec.IIT 34
Example Val and Ref Type Cont…

• Class2 ref2 = ref1;


• ref2.refValue=10;
• Console.WriteLine(ref1.refValue);
• Console.WriteLine(ref2.refValue);
• Console.ReadLine();
• }
• }
• class Class2
• {
• public int refValue;
• }
Amjad Mehmood
Lec.IIT 35
A simple car class in C#

• Public class car


• {
– Int length;
– Int weight;
– Int wheels;
» Public Car()
» {}
» Public void Move()
» {}

Amjad Mehmood
Lec.IIT 36
Interface
• Interface interfaceCar
• {
• Void Move();
• Void Stop();
• }

• Class Car1:interfaceCar
• {
• Void Move()
• {
• //wirte code
• }
• Void Stop()
• {
• //write code here
• }
• }
Amjad Mehmood
Lec.IIT 37
Delegate
• namespace Example
• {
• using System;
• /// <summary>
• /// Delegatge
• /// </summary>
• delegate void FirstDelegate();//declare the delegate
• public class Delegate1
• {
• public static void hello()
• {
• Console.WriteLine("Hello Delegate");
• }
• public static int Main(string[] args)
• {
• FirstDelegate fd=new FirstDelegate(hello);// Instantiation
• fd();// invocation of the delgate
• return 0;
• }
• }
Amjad Mehmood
• } Lec.IIT 38
Object

• All the types In C# are directly or indirectly derived


from Object Type.

Amjad Mehmood
Lec.IIT 39
String

• The string type is directly inherited from the object


type.
• Sring is an alias for System.String class
• This is sealed type.

Amjad Mehmood
Lec.IIT 40
Conversion of the Type

Three ways to convert from one type to another:

• Implicit conversion
• Explicit conversion via casting
• Use of a conversion method

Amjad Mehmood
Lec.IIT 41
Implicit conversion

• using System;
• public class testConversion1
• {
• public static void Main()
• {
• int i=7;
• long l=i;
• Console.WriteLine("The long is converted to int {0}",i);
• }
• }

Amjad Mehmood
Lec.IIT 42
Implicit conversion

• double F;
• int X = 2;
• F = X; // implicit conversion

Amjad Mehmood
Lec.IIT 43
Explicit conversion via casting

• using System;
• public class testConversion1
• {
• public static void Main()
• {
• long l=2.0;
• int i=l;
• Console.WriteLine("The long is converted to int {0}",i);
• }
• }

Amjad Mehmood
Lec.IIT 44
Explicit conversion via casting

• {
• byte b=90,c=45;
• byte d=b+c;
• Console.writeLine(“result is{0}”, d);
• }
• Solution
• byte d=(byte) b+c;
• Console.writeLine(“result is{0}”, d);

• Error messege

Amjad Mehmood
Lec.IIT 45
Use of a conversion method

• Sytem.Convert.ToString
• Sytem.Convert.ToInt
• Sytem.Convert.ToBoolean

• string s = i.ToString();

Amjad Mehmood
Lec.IIT 46
Boxing and Unboxing
• When a value type is converted into a reference type then it is
known as boxing

• When a reference type is converted into value type then it is


knowing as unboxing

• Int b=145;
• Object o=b;//Boxing (implicit converted into object)
• Int j=(int) o;//UnBoxing(explicitly converted into int)
• Console.writeLine(“result is{0}”, j);

Amjad Mehmood
Lec.IIT 47
Modifiers in C#

• Modifiers are keywords used to specify the


declared accessibility of a member or a type.
• Access modifiers are
1. Public
2. Protected
3. Internal
4. Private

Amjad Mehmood
Lec.IIT 48

internal
using System;
• internal class myFirst
• {
• public void hello()
• {
• Console.WriteLine("Hello C#");
• }
• }
• public class Mainclass
• {
• public static void Main()
• {
• myFirst m=new myFirst();
• m.hello();
• }
• }
Amjad Mehmood
Lec.IIT 49
Other modifiers are

• Abstract
• Sealed
• Virtual
• New
• Override
• Static

Amjad Mehmood
Lec.IIT 50
Using Abstract Classes and Methods
• using System;
• abstract class abshello
• {
• protected string s = "";
• public abstract void callhello();
• }

• class absDerived : abshello


• {
• public override void callhello()
• {
• s="Hello C#";
• Console.WriteLine("{0}",s);
• }
• }

• class mainclass
• {
• public static void Main()
• {
• absDerived ad =new absDerived();
• ad.callhello();
• }
• }

Amjad Mehmood
Lec.IIT 51
• using System;
• abstract class abshello
• {
• protected string s = "";
• public abstract void callhello();
• public abstract void sayhello();// not implemented in the derived
• //class.
• }

• class absDerived : abshello


• {
• public override void callhello()
• {
• s="Hello C#";
• Console.WriteLine("{0}",s);
• }
• }

• class mainclass
• {
• public static void Main()
• {
• absDerived ad =new absDerived();
• ad.callhello();
• }
• }
Amjad Mehmood
Lec.IIT 52
There are a few points to note about abstract
classes and methods:

• You cannot create objects of an abstract class.


• You cannot mark a constructor as abstract.
• You may use an abstract class to derive other classes,
including other abstract classes.
• You must override any abstract methods in a base class with
methods that contain code in a derived class.

Amjad Mehmood
Lec.IIT 53
Declaring Sealed Classes and Methods

• Sealed Classes

• cannot use a sealed class to derive a class.


• You mark a class or method as sealed using the sealed keyword. The following example
declares a sealed class:
• sealed public class MotorVehicle { ... }

• Sealed Methods

• cannot override a sealed method in a derived class. may declare a sealed method
in a non-sealed class, but that sealed method cannot be overridden in a derived
class.
• e.g sealed public override void Accelerate( )
Amjad Mehmood
Lec.IIT 54
Sealed Classes
• using System;

• sealed class abshello


• {
• protected string s = "";
• public virtual void callhello()
• {
• s="No Hello to C#";
• }
• }


class absDerived : abshello // Error
• {
• public override void callhello()
• {
• s="Hello C#";
• Console.WriteLine("{0}",s);
• }
• }

• class mainclass
• {
• public static void Main()
• {
• absDerived ad =new absDerived();
• ad.callhello();

Amjad Mehmood
}
Lec.IIT 55
Override
• using System;
• class abshello
• {
• protected string s = "";
• public void callhello()
• {
• s="No Hello to C#";
• }
• }

• class absDerived : abshello


• {
• public override void callhello()
• {
• s="Hello C#";
• Console.WriteLine("{0}",s);
• }
• }

• class mainclass
• {
• public static void Main()
• {
• Amjad
absDerived ad =new Mehmood
absDerived();
• ad.callhello(); Lec.IIT 56
• using System; Static
• class absDerived {
• string s="Hello C#";
• public static void callhello()
• {
• Console.WriteLine("{0}",s);
• }
• public void normal()
• {
• Console.WriteLine("{0}",s);
• }
• }

• class mainclass
• {
• public static void Main()
• {
• absDerived.callhello();
• absDerived a=new absDerived();
• a.normal();
• }
Amjad Mehmood
• } Lec.IIT 57
Virtual
• using System;

• class shibi
• {
• public void hand() { Console.WriteLine("shibi's hand"); }
• public virtual void eye() { Console.WriteLine("shibi's eye"); }
• }
• class myson: shibi
• {
• public void hand() { Console.WriteLine("myson's hand"); }
• public override void eye() { Console.WriteLine("myson's eye"); }
• }
• class Test
• {
• static void Main() {
• shibi s=new shibi();
• myson m = s;
• s.hand();
• m.hand();
• s.eye();
• m.eye();
• }
• }

• whenever you call the virtual method it will search for the overriden method in the deri
Amjad Mehmood
Lec.IIT 58
IL Disassembler (ILDASM)
• Go to Start—visual studio commamd prompt and
type ildasm.exe Microsoft .NET Framework IL
Disassembler (ILDASM). (Debug)

Amjad Mehmood
Lec.IIT 59
Amjad Mehmood
Lec.IIT 60
Flow Control
• Conditional Statements
• The if Statement
• if (condition)
• statement(s)
• else
• statement(s)
• bool isZero;
• if (i == 0)
• {
• isZero = true;
• Console.WriteLine("i is Zero");
• }
• else
• {
• isZero = false;
• Console.WriteLine("i is Non-zero");
• }

Amjad Mehmood
Lec.IIT 61

Else-if
using System;
• namespace
• Wrox.ProCSharp.Basics
• {
• class MainEntryPoint
• {
• static void Main(string[] args)
• {
• Console.WriteLine("Type in a string");
• string input;
• input = Console.ReadLine();
• if (input == "")
• {
• Console.WriteLine("You typed in an empty string"); }
• else if (input.Length < 5)
• {
• Console.WriteLine("The string had less than 5 characters");
• }
• else if (input.Length < 10)
• {
• Console.WriteLine("The string had at least 5 but less than 10 characters"); }
Console.WriteLine("The string was " + input); } } }

Amjad Mehmood
Lec.IIT 62
The switch Statement
• switch (integerA)
• {
• case 1:
• Console.WriteLine("integerA =1"); break;
• case 2:
• Console.WriteLine("integerA =2"); break;
• case 3:
• Console.WriteLine("integerA =3"); break;
• default:
• Console.WriteLine("integerA is not 1,2, or 3"); break;
• }

Amjad Mehmood
Lec.IIT 63
Loops
• The for Loop
• The syntax is:
• for (initializer; condition; iterator) statement(s)

• static void Main(string[] args)
• {
• // This loop iterates through rows...
• for (int i = 0; i < 100; i+=10)
• {
• // This loop iterates through columns...
• for (int j = i; j < i + 10; j++)
• {
• Console.Write(" " + j);
• }
• Console.WriteLine();
• }
• }

Amjad Mehmood
Lec.IIT 64
The while Loop

• while(condition)
• statement(s);

• bool condition = false;


• while (!condition)
• {
• DoSomeWork();
• condition = CheckCondition();
• }
Amjad Mehmood
Lec.IIT 65
The do…while Loop

• bool condition;
• Do
• {
• // this loop will at least execute once, even if
condition = CheckCondition();
• } while (condition);

Amjad Mehmood
Lec.IIT 66
The foreach Loop

• foreach (int temp in arrayOfInts)


• {
• Console.WriteLine(temp);
• }

Amjad Mehmood
Lec.IIT 67
Jump Statements

• The goto Statement


• goto Label1;
• Console.WriteLine("This won't be executed");

• Label1: Console.WriteLine("Continuing execution


from here");

Amjad Mehmood
Lec.IIT 68
Statements in branching

• The break Statement


• The continue Statement
• The return Statement

Amjad Mehmood
Lec.IIT 69
Arrays

array name is an lvalue


Every array in C# “knows” its own length. The length of the array is determined by
theexpression: c.Length

Types of arrays
Two main types
One Dimensional Arrays
Multidimensional Arrays

1. One Dimensional Arrays


In One Dimensional arrays we can use a single subscript to refer the data elements.
One Dimensional arrays consists of one column and more than one rows.
E.g.
int [ ] arr1={1,2,3};
2. Multidimensional Arrays
Multidimensional arrays we use more than one subscript to refer the data elements
E.g.
int [ , ] arr1={{2,4,5},{5,4,7},{8,7,9}}; Amjad Mehmood
Lec.IIT 70
One Dimensional Arrays

Amjad Mehmood
Lec.IIT 71
Arrays

• The declaration
• int[ ] c = new int[ 12 ];

The preceding statement can also be performed in two steps as follows:

• int[ ] c; // declares the array


• c = new int[ 12 ]; // allocates the reference to the
array

Amjad Mehmood
Lec.IIT 72
Allocating an Array and Initializing Its Elements

• class InitArray
• {
• // main entry point for application
• static void Main( string[] args )
• {
• string output = "";
• int[] x; // declare reference to an array
• x = new int[ 10 ]; // dynamically allocate array and set
• // default values

• int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
• const int ARRAY_SIZE = 10; // named constant
• int[] z; // reference to int array
Amjad Mehmood
Lec.IIT 73
Allocating an Array and Initializing Its Elements

• // allocate array of ARRAY_SIZE (i.e., 10) elements


• z = new int[ ARRAY_SIZE ];
• // set the values in the array
• for ( int i = 0; i < z.Length; i++ )
• z[ i ] = 2 + 2 * i;

• output += "Subscript\tArray x\tArray y\tArray z\n";


• // output values for each array
• for ( int i = 0; i < ARRAY_SIZE; i++ )
• output += i + "\t" + x[ i ] + "\t" + y[ i ] +
• "\t" + z[ i ] + "\n";

• MessageBox.Show( output,
• "Initializing an array of int values",
• MessageBoxButtons.OK, MessageBoxIcon.Information );
• } // end Main
• } // end class InitArray Amjad Mehmood
Lec.IIT 74
Output …

Amjad Mehmood
Lec.IIT 75
Totaling the Elements of an Array

• class SumArray
• {
• // main entry point for application
• static void Main( string[] args )
• {
• int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
• int total = 0;
• for ( int i = 0; i < a.Length; i++ )
• total += a[ i ];
• MessageBox.Show( "Total of array elements: " + total,
• "Sum the elements of an array",
• MessageBoxButtons.OK, MessageBoxIcon.Information );
• } // end Main
• } // end class SumArray

Amjad Mehmood
Lec.IIT 76
Passing Arrays to Methods

• int[] hourlyTemperatures = new int[ 24 ];


• The method call
• ModifyArray( hourlyTemperatures );

• The method header for method ModifyArray might be written as


• public void ModifyArray( int[] b )

Amjad Mehmood
Lec.IIT 77
• private void showOutputButton_Click( object sender,
• System.EventArgs e )
• {
• int[] a = { 1, 2, 3, 4, 5 };
• outputLabel.Text = "Effects of passing entire array " +

• "call-by-reference:\n\nThe values of the original " +


• "array are:\n\t";
• for ( int i = 0; i < a.Length; i++ )
• outputLabel.Text += " " + a[ i ];
• ModifyArray( a ); // Array is passed by reference
• outputLabel.Text +=
• "\n\nThe values of the modified array are:\n\t";
• // display elements of array a
• for ( int i = 0; i < a.Length; i++ )
• outputLabel.Text += " " + a[ i ];
• outputLabel.Text += "\n\nEffects of passing array " +
• "element call-by-value:\n\na[ 3 ] before " +
• "ModifyElement: " + a[ 3 ];
• // Array element passed call-by-value
• ModifyElement( a[ 3 ] );
• outputLabel.Text +=
• "\na[ 3 ] after ModifyElement: " + a[Amjad
3 ]; Mehmood
• } Lec.IIT 78
• // method modifies the array it receives,
• // original will be modified
• public void ModifyArray( int[] b )
• {
• for ( int j = 0; j < b.Length; j++ )
• b[ j ] *= 2;
• }
• // method modifies the integer passed to it
• // original will not be modified

• public void ModifyElement( int e )


• {
• outputLabel.Text +=
• "\nvalue received in ModifyElement: " + e;
• e *= 2;
• outputLabel.Text +=
• "\nvalue calculated in ModifyElement: " + e;
• }
• } Amjad Mehmood
Lec.IIT 79
Types of Multidimensional arrays
Two types
1. Rectangular array
2. Jagged Array

1. Rectangular array
In rectangular arrays every row of the array is of the same length.
OR
All the rows have the same numbers of elements
EXAMPLE
Int [ , ] arr1=new int [ , ]{{ 3,5,7,9},{11,13,15,17}};

OR
Int [ , ] arr1={{2,4,6,8,},{10,12,14,16}};

Amjad Mehmood
Lec.IIT 80
DIAGRAM OF RECTANGULAR ARRAYS

Stack
Heap
arr1
3 5 7 9
11 13 15 17

Amjad Mehmood
Lec.IIT 81
• using System ;
• class rectarray
• {
• static void Main ( string[ ] args )
• {
• int [ , ] arr1 = new int [ 2, 3 ] { { 1, 2, 3 }, { 4, 5, 6 } } ;
• int [ , ] arr2 = new int [ 2, 3 ] ;

• Console.WriteLine ( "Elements of arr1: " ) ;


• for ( int i = 0 ; i < arr1.GetLength( 0 ) ; i++ )
• {
• for ( int j = 0 ; j < arr1.GetLength( 1 ) ; j++ )
• Console.Write ( arr1 [ i, j ] ) ;
• Console.WriteLine( ) ;
• }
Amjad Mehmood
Lec.IIT 82
Console.WriteLine ( "Number of elements in arr1: " + arr1.Length ) ;
• Array.Copy ( arr1, 2, arr2, 2, 3 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• arr2.SetValue ( 5, 0, 1 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Array.Clear ( arr2, 0, arr2.Length ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i ) ;
• }
• }
Amjad Mehmood
Lec.IIT 83
2. Jagged Array
• A jagged array is an array of several one dimension arrays of different length.
• Array of Array e.g
Int [ ] [ ] arr1=new int [2] [ ];
arr1 [0 ]=new int [3 ] { 3 ,5 7 1 };
arr1 [ 1]= new int [2]{11,13};
In the memory the jagged array is shown as

Stack Heap

arr1[0] 3 5 7 9

arr1[1] 11 13
arr1

Amjad Mehmood
Lec.IIT 84
EXAMPLE
• using System ;
• class jaggedarray
• {
• static void Main ( string[ ] args )
• {
• int [ ][ ] arr1 = new int [ 2 ] [ ] ;
• arr1 [ 0 ] = new int [ 3 ] { 1, 2, 3 } ;
• arr1 [ 1 ] = new int [ 2 ] { 4, 5 } ;
• Console.WriteLine ( "Elements of arr1: " ) ;
• for ( int i = 0 ; i < arr1.Length ; i++ )
• {
• for ( int j = 0 ; j < arr1[ i ].Length ; j++ )
• Console.Write ( arr1 [ i ] [ j ] ) ;
• Console.WriteLine( ) ;
• }
• }
• }
Amjad Mehmood
Lec.IIT 85
The System.Array Type

The System. Array class automatically becomes the


base class of any type of array
The array class provides methods for creating
manipulating , searching , and storing arrays .

Amjad Mehmood
Lec.IIT 86
EXAMPLE
• using System ;
• class onedarray
• {
• static void Main ( string[ ] args )
• {
• int[ ] arr1 = new int [ 5 ] { 1, 4, 7, 8, 9 } ;
• int[ ] arr2 = new int [ 10 ] ;

• arr1.CopyTo ( arr2, 0 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;

• arr2.SetValue ( 5, 0 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;

• Console.WriteLine ( "Number of elements in arr1:" + arr1.Length ) ;


• Console.WriteLine ( "Number of elements in arr2:" + arr2.Length ) ;

Amjad Mehmood
Lec.IIT 87
• Array.Copy ( arr1, 2, arr2, 6, 2 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;

• Array.Reverse ( arr2 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " ") ;
• Console.WriteLine( ) ;

• Array.Sort ( arr2 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;

• Console.WriteLine ( "Index of 8 is " + Array.IndexOf ( arr2, 8 ) ) ;

• Array.Clear ( arr2, 3, 3 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;
• }
• }

Amjad Mehmood
Lec.IIT 88
String
• The string is a data type in C# holds the text enclosed in double quotes.
• String is the alias of System. String
• Instance of the string type represent Unicode character strings
EXAMPLE
string s=“Hello”;
• using System;
• namespace sample
• {
• class Class1
• {
• static void Main ( string[ ] args )
• {
• string s1 = "Good Morning" ;
• string s2 ;
• s2 = s1 ;
• s1 = "Wake Up" ;
• Console.WriteLine ( s1 ) ;
• Console.WriteLine ( s2 ) ;

• } OUTPUT
• } Wake up
• } Good Morning
Press any key to continue

Amjad Mehmood
Lec.IIT 89
@ Symbol
• C# support two types of string variables quoted and @- quoted.
• If we do not want the compiler to process escape sequences then we use @-quoted string a
prefix
• @ -qouted string simplifies the expression path names
EXAMPLE
string s2=@ “C:\Articles\text.txt”; equilent to
string s2= “C:\\Articles\\text.txt”;

Escape Sequence
Escape sequence print out the tabs
EXAMPLE
String s1=“hi \t there”;
OUTPUT
hi there
Amjad Mehmood
Lec.IIT 90
System. String type
System. String class performs various operations on string data type
EXAMPLE
• using System ;
• namespace sample
• {
• class Class1
• {
• static void Main ( string[ ] args )
• {
• string s1 = "kicit" ;
• string s2 = "Nagpur" ;
• Console.WriteLine ( "Char at 3rd position: " + s1 [ 2 ] ) ;

• string s3 = string.Concat ( s1, s2 ) ;


• Console.WriteLine ( s3 ) ;
• Console.WriteLine ( "Length of s3: " + s3.Length ) ;

• s3 = s3.Replace ( 'p', 'P' ) ;


• Console.WriteLine ( s3 ) ;

• s3 = string.Copy ( s2 ) ;
• Console.WriteLine ( s3 ) ;

• int c = s2.CompareTo ( s3 ) ;
• if ( c < 0 )
• Console.WriteLine ( "s2 is less than s3" ) ;
Amjad Mehmood

Lec.IIT 91
• if ( c == 0 )
• Console.WriteLine ( "s2 is equal to s3" ) ;
• if ( c > 0 )
• Console.WriteLine ( "s2 is greater than s3" ) ;

• if ( s1 == s3 )
• Console.WriteLine ( "s1 is equal to s3" ) ;
• else
• Console.WriteLine ( "s1 is not equal to s3" ) ;

• s3 = s1.ToUpper( ) ;
• Console.WriteLine ( s3 ) ;

• s3 = s2.Insert ( 6, "Mumbai" ) ;
• Console.WriteLine ( s3 ) ;

• s3 = s2.Remove ( 0, 1 ) ;
• Console.WriteLine ( s3 ) ;

• int fin = s1.IndexOf ( 'i' ) ;


• Console.WriteLine ( "First index of i in s1: " + fin ) ;

• int lin = s1.LastIndexOf ( 'i' ) ;


• Console.WriteLine ( "Last index of i in s1: " + lin ) ;

• string sub = s1.Substring ( fin, lin ) ;


• Console.WriteLine ( "Substring: " + sub ) ;

• }
• } Amjad Mehmood
• } Lec.IIT 92
Parsing String to other data types
• Console.ReadLine() can take input as a string from the user.
• We need to type cast string for mathematical operations .
• For this we need Parse() method to type cast string into other data type .
• using System ;
• namespace sample
• {
• class Class1
• {
• static void Main ( string[ ] args )
• {
• Console.WriteLine ( "Enter an integer: " ) ;
• string s = Console.ReadLine( ) ;
• int i = int.Parse ( s ) ;

• Console.WriteLine ( "Enter a float: " ) ;


• s = Console.ReadLine( ) ;
• float f = float.Parse ( s ) ;

• float t = f + i ;
• Console.WriteLine ( t ) ;
• }
• }
Amjad Mehmood
• }
Lec.IIT 93
Windows Form Controls

Amjad Mehmood
Lec.IIT 94
Windows Form Controls

• Control: A control is anything on a form that a user


can interact with. For example,
Buttons,Labels, textBoxes, toolbars etc.
• Form: A form is a container for controls.
• .Net provide a rich set of forms like windows forms,
web forms, mobile forms etc. Each have its own set
of controls

Amjad Mehmood
Lec.IIT 95
Common Windows Form Controls

• Buttons
• TextBoxes
• Labels
• ComboBox
• Radio buttons
• CheckBoxes
• PictureBoxes
• Toolbars etc

Amjad Mehmood
Lec.IIT 96
Amjad Mehmood
Lec.IIT 97
• All Controls have three things in common
 All have a set of properties
 All have a set of events to which the control can respond
 All have methods (Functions) that can be used for performing
different operations related to that control.

 Properties:
Properties are the characteristics that can
describe a control and can be muted at runtime.
e.g Name of control,text,backcolr,forecolor
etc.

Amjad Mehmood
Lec.IIT 98
Common Properties

All controls have a common set of properties


Some of these are follow.
 Name, text
 backcolor, forecolor
 anchor, dock
 image, size, location, visible etc.
All these properties (except Name) can be edited at design time as
well as at runtime.

Amjad Mehmood
Lec.IIT 99
Event

• An event is any user action, or a system action that


can be recognized by O.S and can execute some code
against it.
• Events can be handle at two levels when they are
raised.
1. At Application Level
2. At O.S Level (HOOKS)
• Event Handler: It is a function that is executed when
an event is raised.

Amjad Mehmood
Lec.IIT 100
• An event handler may be of two types
1. Local
2. Global
Local event handlers are executed when an event at
application level is raised and there is no hook
installed for it.
Hook: A hook is a function that is executed before the
event reaches to your application. e.g. stopping an
application from running before it starts.

Amjad Mehmood
Lec.IIT 101
• Global event handlers (HOOKS):
are executed at O.S level. For example if we write a
Hook for a click event. Then it will be executed each
time a click occurs even if it is out of your
application.

Amjad Mehmood
Lec.IIT 102
Event-Handling Model

calls Handler 1 for event E


calls
Object A raises event E Delegate for event E Handler 2 for event E

Handler 3 for event E

Event Handler Parameters


Two parameters are passed.
1. Sender: it describes that who raises the
event. i.e it identifies the event raiser.
2. System.EventArgs: this contains information that is specific to the event.
For example, what are x,y co-ordinates where the event occurs.

void button1_click(object sender,System.EventArgs e)

Amjad Mehmood
Lec.IIT 103
Common Controls Events

• All controls have some events in common


1. Click 2. Paint ( Raised each time when a control or form is redrawn)
3. MouseDown 4. MouseEnter
5. MouseLeave
6. MouseUP 7.KeyDown
8 .KeyPress
And many many more…

Amjad Mehmood
Lec.IIT 104
Methods

• Each controls have a rich set of methods that can


easy the task for carrying different operations related
to a control.

Amjad Mehmood
Lec.IIT 105
Amjad Mehmood
Lec.IIT 106
Amjad Mehmood
Lec.IIT 107
Amjad Mehmood
Lec.IIT 108
Amjad Mehmood
Lec.IIT 109
Amjad Mehmood
Lec.IIT 110
Amjad Mehmood
Lec.IIT 111
Amjad Mehmood
Lec.IIT 112
Simple application

Amjad Mehmood
Lec.IIT 113
Amjad Mehmood
Lec.IIT 114
Amjad Mehmood
Lec.IIT 115
Amjad Mehmood
Lec.IIT 116
Amjad Mehmood
Lec.IIT 117
Amjad Mehmood
Lec.IIT 118
Amjad Mehmood
Lec.IIT 119
Amjad Mehmood
Lec.IIT 120
Amjad Mehmood
Lec.IIT 121
Amjad Mehmood
Lec.IIT 122
Amjad Mehmood
Lec.IIT 123
Amjad Mehmood
Lec.IIT 124
Amjad Mehmood
Lec.IIT 125
Amjad Mehmood
Lec.IIT 126
Amjad Mehmood
Lec.IIT 127
Amjad Mehmood
Lec.IIT 128
Amjad Mehmood
Lec.IIT 129
Use of Message Box

Amjad Mehmood
Lec.IIT 130
Simple Program: Adding Integers

Amjad Mehmood
Lec.IIT 131
Amjad Mehmood
Lec.IIT 132
Submit Button Code
• string info="Name: "+txtName.Text+"\nFather Name:"+txtFName.Text;

• if(rdMale.Checked)

» info=info+"\nGeneder"+rdMale.Text;

• else
• info=info+"\nGender:"+rdFemale.Text;
info=info+"\n Hobbies:\n";

• if(ChckCricket.Checked)
• info=info+ChckCricket.Text+"\n";

• if(chckHocky.Checked)
• info=info+chckHocky.Text+"\n";

• if(chckFootball.Checked)
• info=info+chckFootball.Text+"\n";

• if(chckTennis.Checked)
• info=info+chckTennis.Text+"\n";
• info=info+"\nJob Title: "+Title.Text;
• info=info+"\nSalary: "+combSalary.Text;

MessageBox.Show(info);
Amjad Mehmood
Lec.IIT 133
Quiz# 02
Time Allowed:10 Minutes
Marks:10

• I'm confused. What's the difference between the .NET


Framework and Visual Studio .NET?
• Should I write all my code in C# because it runs more
efficiently than Visual Basic .NET or COBOL .NET?
• What is CLS and CTS and who performs these functions
• Write the purpose of new operator
• What is Boxing and UnBoxing?
• Draw the execution diagram of .net environment
• Override the Tostring Method
• What is up casting and down casting
• What are the rules for Declaring Sealed Classes and Methods
Amjad Mehmood
Lec.IIT 134
Methods

• Note that official C# terminology does in fact make a


distinction between functions and methods.
• In this terminology, the term 'function member'
includes not only methods, but also other non-data
members of a class or struct. This includes indexers,
operators, constructors, destructors, and also –
perhaps somewhat surprisingly – properties.
• These are contrasted with data members: fields,
constants, and events.

Amjad Mehmood
Lec.IIT 135
Declaring Methods

• [modifiers] return_type MethodName([parameters])

• {
• // Method body
• }

Amjad Mehmood
Lec.IIT 136
Invoking Methods
• using System;
• namespace Wrox.ProCSharp.Basics
• {
• class MainEntryPoint
• {
• static void Main()
• {
• // Try calling some static functions
• Console.WriteLine("Pi is " + MathTest.GetPi());
• int x = MathTest.GetSquareOf(5);
• Console.WriteLine("Square of 5 is " + x);
• // Instantiate at MathTest object
• MathTest math = new MathTest(); // this is C#'s way of //
• instantiating a reference type
• // Call non-static methods math.value = 30;
• Console.WriteLine( "Value field of math variable contains " + math.value);
• Console.WriteLine("Square of 30 is " + math.GetSquare());
• }
• }

Amjad Mehmood
Lec.IIT 137
Invoking Methods
• // Define a class named MathTest on which we will call a method
• class MathTest
• {
• public int value;
• public int GetSquare()
• {
• return value*value;
• }
• public static int GetSquareOf(int x)
• { return x*x; }
• public static double GetPi()
• {
• return 3.14159;
• }
• }
• }

Amjad Mehmood
Lec.IIT 138
Passing Parameters to Methods
• namespace Wrox.ProCSharp.Basics
• {
• class ParameterTest
• {
• static void SomeFunction(int[] ints, int i)
• {
• ints[0] = 100; i = 100;
• }
• public static int Main()
• {
• int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; // Display the original values Console.WriteLine("i = " + i);
• Console.WriteLine("ints[0] = " + ints[0]);
• Console.WriteLine("Calling SomeFunction..."); // After this method returns, ints will be changed,
• // but i will not SomeFunction(ints, i);
• Console.WriteLine("i = " + i);
• Console.WriteLine("ints[0] = " + ints[0]);
• return 0;
• }
• }
• }

Amjad Mehmood
Lec.IIT 139
Passing Parameters to Methods
• namespace Wrox.ProCSharp.Basics
ParameterTest
• {
• class ParameterTest i=0
• {


static void SomeFunction(int[] ints, int i)
{
ints[0] = 0
• ints[0] = 100; i = 100; }
• public static int Main() Calling SomeFunction...


{ i=0
int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; // Display the original values
• Console.WriteLine("i = " + i);
• Console.WriteLine("ints[0] = " + ints[0]); ints[0] = 100
• Console.WriteLine("Calling SomeFunction..."); // After this method returns, ints
• will be changed, // but i will not
• SomeFunction(ints, i);
• Console.WriteLine("i = " + i);
• Console.WriteLine("ints[0] = " + ints[0]);
• return 0; } } }

Amjad Mehmood
Lec.IIT 140
reference-type behavior

• static void SomeFunction(int[] ints, ref int i)


• {
• ints[0] = 100; i = 100;
• }
• We will also need to add the ref keyword when we
invoke the method:
• SomeFunction(ints, ref i);

Amjad Mehmood
Lec.IIT 141
The out Keyword
• out parameter isn't assigned a value within the body of the function, the
method won't compile.
• static void SomeFunction(out int i)
• {
• i = 100;
• }
• public static int Main()
• {
• int i; // note how i is declared but not initialized
• SomeFunction(out i);
• Console.WriteLine(i);
• return 0;
• }

Amjad Mehmood
Lec.IIT 142
Array

• int[] integers;
• To initialize the array with specific dimensions, we
can use the new keyword, giving the size in the
square brackets after the type name:
• // Create a new array of 32
• ints int[] integers = new int[32];
• integers[31] = 432;

Amjad Mehmood
Lec.IIT 143
Array

• string[] myArray = {"first element", "second


element", "third element"};
• Note that it is perfectly permissible to use a variable
to set how many elements the array will contain, like
this:
• int len;
• len = GetArraySize(); // assume this function works
out how big we want //
• the array to be string[] myArray = new string[len];

Amjad Mehmood
Lec.IIT 144
unchecked
• Working with Arrays
• Arrays
• int arrayLength = integers.Length;
• using the static Array.Sort() method:
Array.Sort(myArray);
System.Array.Sort() method
• using the static Reverse() method:
• Array.Reverse(myArray);
• string[] artists = {"Leonardo", "Monet", "Van Gogh", "Klee"};
Array.Sort(artists);
• Array.Reverse(artists);
• foreach (string name in artists)
• {
• Console.WriteLine(name);
• }

Amjad Mehmood
Lec.IIT 145
Operators
• Arithmetic+ - * / %
• Logical& | ^ ~ && || !
• String concatenation+
• Increment and decrement++ --
• Bit shifting<< >>
• Comparison== != < > <= >=
• Assignment= += -= *= /= %= &= |= ^= <<= >>=
• Member access (for objects and structs).
• Indexing (for arrays and indexers)[]
• Cast()
• Conditional (the Ternary Operator)?: Object Creationnew Type
informationsizeof (unsafe code only) is typeof as Overflow exception
controlchecked unchecked Indirection and Address* -> & (unsafe code
only) []

Amjad Mehmood
Lec.IIT 146
Operator Shortcuts
• The following table shows the full list of shortcut assignment operators available
in C#:
• Shortcut OperatorEquivalent To
• x++, ++x x = x + 1
• x--, --x x=x–1
• x += y x=x+y
• x -= y x=x–y
• x *= y x=x*y
• x /= y x=x/y
• x %= y x=x%y
• x >>= y x = x >> y
• x <<= y x = x << y
• x &= y x=x&y
• x |= y x=x|y
• x ^= y x=x^y

Amjad Mehmood
Lec.IIT 147
Checked and Unchecked
• When we try to run this, we will get an error message like this:
Unhandled Exception: System.OverflowException: Arithmetic operation
• Consider the following code:
• byte b = 255;
• b++;
• Console.WriteLine(b.ToString());
• byte b = 255;
• checked
• {
• b++;
• }
• Console.WriteLine(b.ToString());

Amjad Mehmood
Lec.IIT 148
unchecked
• no exception will be raised, but we will lose data –
since the byte type can't hold a value of 256, the
overflowing bits will be discarded, and our b variable
will hold a value of zero.
• byte b = 255;
• unchecked
• {
• b++;
• }
• Console.WriteLine(b.ToString());
Amjad Mehmood
Lec.IIT 149
is
• The is operator allows us to check whether an object is
compatible with a specific type. For example, to check
whether a variable is compatible with the object type:
• By the phrase is 'compatible', we mean that an object is either
of that type or is derived from that type.
• int i = 10;
• if (i is object)
• {
• Console.WriteLine("i is an object");
• }

Amjad Mehmood
Lec.IIT 150
sizeof
• We can determine the size (in bytes) required by a
value type on the stack using the sizeof operator:
• string s = "A string";
• Unsafe
• {
• Console.WriteLine(sizeof(int));
• }
• This will display the number 4, as ints are four bytes
long
Amjad Mehmood
Lec.IIT 151
Enumerations

• An enumeration is a user-defined integer type.


• We can define an enumeration as follows:
• public enum TimeOfDay
• {
• Morning = 0,
• Afternoon = 1,
• Evening = 2
• }
• We can now access these values as members of the
enumeration. For example, TimeOfDay.Morning will retur
the value 0.
Amjad Mehmood
Lec.IIT 152
Enum Example
• class EnumExample
• {
• public static int Main()
• {
• WriteGreeting(TimeOfDay.Morning);
• return 0;
• }
• static void WriteGreeting(TimeOfDay timeOfDay)
• {
• switch(timeOfDay)
• {
• case TimeOfDay.Morning: Console.WriteLine("Good morning!"); break;
• case TimeOfDay.Afternoon: Console.WriteLine("Good afternoon!"); break;
• case TimeOfDay.Evening: Console.WriteLine("Good evening!"); break; default:
• Console.WriteLine("Hello!"); break; } } }

Amjad Mehmood
Lec.IIT 153
How to retrieve the string?

• You can retrieve the string representation of an


enum. For example, using our earlier TimeOfDay
enum:
• TimeOfDay time = TimeOfDay.Afternoon;
Console.WriteLine(time.ToString());

Amjad Mehmood
Lec.IIT 154
Classes and Inheritance
• class MyClass
• {
• private int someField;
• public string SomeMethod(bool parameter)
• {}
• }
• MyClass myObject;
• myObject = new MyClass();
• You can, in fact, declare and initialize an instance at the same time:
• MyClass myObject = new MyClass();
• Consider the following line:
• MyClass myObjectRef = myObject;
• myObjectRef will also refer to the same MyClass() instance as myObject.

Amjad Mehmood
Lec.IIT 155
Single Implementation Inheritance

• C# supports single inheritance of classes. In other


words, a class may derive directly from one other
class. The syntax for this is as follows.
• class MyDerivedClass : MyBaseClass
• {
• // functions and data members here
• }

Amjad Mehmood
Lec.IIT 156
Method Overloading

C# supports method overloading – several versions of the


method that have
different signatures (name, number of parameters, and
parameter types),
In order to overload methods, you simply declare the methods
with the same name but different numbers or types of
parameters:
• class ResultDisplayer
• {
• void DisplayResult(string result) { // implementation }
• void DisplayResult(int result) { // implementation }
• }
Amjad Mehmood
Lec.IIT 157
Method Overriding and Hiding

• class MyBaseClass
• {
• public virtual string VirtualMethod()
• {
• return "This method is virtual and defined in MyBaseClass";
• }
• }
• class MyDerivedClass : MyBaseClass
• {
• public override string VirtualMethod()
• {
• return "This method is an override defined in MyDerivedClass";
• }
• }

Amjad Mehmood
Lec.IIT 158
Method Overriding and Hiding

• class MyDerivedClass : HisBaseClass


• {
• public new int MyGroovyMethod()
• {
• // some groovy implementation
• }
• }

Amjad Mehmood
Lec.IIT 159
Properties
• To define a property in C#, we use the following syntax.
• public string SomeProperty
• {
• get
• {
• return "This is the property value";
• }
• Set
• {
• // do whatever needs to be done to set the property
• }
• }

Amjad Mehmood
Lec.IIT 160
Properties Cont…
• private string foreName;
• public string ForeName
• {
• Get
• {
• return foreName;
• }
• set
• {
• if (value.Length > 20) // code here to take error recovery action //
• (
• eg. throw an exception)
• else foreName = value;
• }
• }

Amjad Mehmood
Lec.IIT 161
Read-Only and Write-Only Properties

• It is possible to create a read-only property by simply


omitting the set accessor from the property definition.

• public string ForeName {


• Get
• {
• return foreName;
• }
• }

• create a write-only property by omitting the get accessor.

Amjad Mehmood
Lec.IIT 162
Inlining

• C# code is compiled to IL then JIT-normally compiled at


runtime to native executable code.
• Well the JIT compiler is designed to generate highly
optimized code.
• Although it is not in general possible to predict what methods
will be inlined in particular circumstances, experience has
shown that the JIT compiler is ruthless when it comes to
inlining any function calls that look suitable.
• A method or property whose implementation simply calls
another method or returns a field will almost certainly be
inlined.
• Decision of where to inline is made entirely by the CLR.
Amjad Mehmood
Lec.IIT 163
Quiz 4
Time: 15 Min Marks: 50

• Write a names of some important namespaces classes in it and


methods
• Difference between heap and stack
• Difference between classes and structures
• Write a class with static constructor which includes day, year,
month and show method which will display the given day,
year and month.
• Differentiate between static constructor static method and
constructor.
• What is enumerators?
• Event-Handling Model
• What is hooks?
• What command is use to load IL Disassembler (ILDASM)?
Amjad Mehmood
Lec.IIT 164
Structure
•Structure is a data structure which contains different data types of data and with there methods.
•Structure is defined using a key word struct.
EXAMPLE
using System;
namespace sample
{
struct employee
{
string name;
int age;
float sal;
public employee(string n,int a,float s)
{
name =n;
age=a;
sal=s;
}
Amjad Mehmood
Lec.IIT 165
public viod showdata()
{
Console.WriteLine(“Name:”+name);
Console.WriteLine(“Age:”+age);
Console.WriteLine(“Salary:”+sal);
}
}
class Class1
{
Static void Main(string [ ] args)
{
employee e1=new employee(“Ali”,35,25000);
e1.showdata();
}
}
}

Amjad Mehmood
Lec.IIT 166
Structure Vs Class
(a) We can not add our own zero argument constructor to the structure
(b) The structures are implicitly sealed . Hence structures can not be inherited
(c) Being sealed structure can not be marked with abstract modifier.
(d) Since structures can’t be inherited , so their members can not have protected access
modifier . Also there can not be virtual methods in structure.
(e) Structure mebers can not be initialized with the point of declaration eg
struct mypoint
{
int i=10;
int j=20;
}
This result in error . However if the member is static then we are permitted to initialize it.
(f) The structures are value type where as classes are reference type.

Amjad Mehmood
Lec.IIT 167
Value type And Reference Type
• The data of value type gets store on the stack while the data of reference type gets stored on the
heap
• The variable of value type directly contains the data, whereas reference type contains
references or address of the data.

Value Type Reference Type

i 10 10

C1

j 20 20

C1 Object

Amjad Mehmood
Lec.IIT 168
EXAMPLE
Using System;
Namespace sample
{
struct mystruct
{
public int I;
}
class Class1
{
static void Main(string [] args)
{
mystruct x=new mystruct();
x.i=9;
mystruct y;
y=x;
y.i=5;
Console.WriteLine(x.i);
Console.WriteLine(y.i);
}
} OUTPUT
} 5 5

Amjad Mehmood
Lec.IIT 169
When to use structure and class
STRUCTURE.
When we group dissimilar data types , we must use structure .
When we want fast access as structures are stored on stack which is faster than heap.

CLASS
Classes are more efficient as only reference is copied but when we pass a structure variable as a
parameter or assign it to another structure variable then the full contents of the structure
variable get copied.

Boxing and unboxing


• When a value type is converted into a refrence type then it is known as boxing
• When a reference type is converted into value type then it is knowing as unboxing
eg.
int i=10;
object obj=i; // Boxing
int j=(int)obj; //unboxing

Amjad Mehmood
Lec.IIT 170
ADO.Net
• .Net managed library that exposes functions to access data that exists outside of an
application. i.e to access persistent data.
• ADO.Net can work both in Connected and Disconnected Manner.

Road To ADO.Net:
“Great things doest not come in impulse but it is a series of small steps.
So ADO.Net is not such that comes in that shape directly that we see
today. But it is a revolutionary form of Microsoft’s Past technologies for
data access.
To understand the history of ADO.Net and Microsoft Data Access
Technologies, we need to understand the following.

Amjad Mehmood
Lec.IIT 171
Data Access Libs( DAO, RDO, ADO, and ADO.Net )

To Connect to DB through

Data Providers ( ODBC and OLEDB )


Can Talk to DB Providers with help of

Translation Layer
Converts User’s Call to appropriate Proprietary Function calls

Amjad Mehmood
Lec.IIT 172
Data Access Today: ( ADO. Net )
ADO. Net is developed for two basic goals.
1. To overcome the problems of existing data access technologies.
2. To cope up with the future data access methods.
ADO. Net Structure:
• ADO. Net have two fundamental parts.
i. DataSets
ii. .Net Data Providers
i. DataSets: Normally, used in Disconnected approach and is used to hold data that comes
from the database. Once, we get data in a dataset, we can insert, delete and update data
in it as if it we are working with database.

ii. .Net Data Providers: .Net data providers are used to extract and post data to a
database. ADO. Net support three sort of providers.

a ). Data Provider for SQL Server b ). Data Provider for OLEDB c ). Data Provider for ODBC
Each of these providers are contained within different namespaces.

Amjad Mehmood
Lec.IIT 173
• ADO. Net Objects and Classes:
• ADO. Net objects can be divided into two categories.
» i. Data Provider Objects
» ii Consumer Objects

ADO. Net Consumer Objects ADO. Net Provider Objects

DataSet Connection

DataTable Command

DataRow CommandBuilder
DataColoumn DataReader
DataRelation DataReader
Amjad Mehmood
Lec.IIT 174
• Data Provider Objects: They are used to extract and post data to a data source. Once extracted the data is put
into the clients memory of client application. Separate provider objects are used to interact with different type of data
sources.
• Data Consumer Objects: Consumer objects are used to hold and manipulate the data that is being extracted with
provider objects. Normally, they are used when we are using the disconnected approach.

3
Consumer Objects hold and RAM Space Reserved for User Application
manipulate the extracted data
Application Extracted Data

1 2
And Places the extracted data 4
in
Provider Objects Extract Data Application reserved RAM
Database
Manipulated data is posted back to
Amjad Mehmood database with provider objects
Lec.IIT 175
• ADO. Net Programming
.Net provides two ways to do database programming.
1. Through Wizards and Objects Manipulation
2. Doing Everything by Coding
1. Wizards provides an easy way to build up database applications but they do not let you to do quite complex
programming.
2. Here programming is little harder but provide everything that you want to do with a database.

Example Program: ( Through Wizard )

Amjad Mehmood
Lec.IIT 176
Steps : 1
( a ) Connecting to Database: First, we need to connect to a database.
1. Click on “Server Explorer and then right click on “Data Connection ” and select
“add Connection “.
2. A wizard connection creation will get started
3. Click on the “Providers tag and select “Microsoft OLE DB Provider for SQL-
Server “ and Click Next.
4. In the sever name text box, give “localhost” and in the database combo box select
any database (here Northwind ) and click on
“Test
“Test Connection button” to check that whether connection has been successfully
created.

4 2
3

Amjad Mehmood
Lec.IIT 177
• ( b ) Adding Data Adapter: Data Adapter is 5
used to perform different sort of operations like
updating data, filling data sets etc.
5. In toolbox, click on “Data” tab and select
“SqlDataAdapter” and a wizard will get started.Click
“Next”

6. In the Next, you are asked to select the “Connection”


that you will use. So select your recently created
“Connection” 6
7. In the next tab, you are asked to select the
“SQL Query type” and you most of times select
“Use Sql Statements”.Click Next 7
and in the next click
“Query Builder Button”.

Amjad Mehmood
Lec.IIT 178
8. Next you will be presented with all the tables present in the database. This time select 8
“Customers” click “Add” and then Close.
9. Next, you will be asked for selecting the “fields” in the table, Check all the fields tab and
click “OK” and “Finish” the wizard.
10. Right click on “DataAdapter1” object created through wizard and select “Generate Data
Set” and if you
do not want to change its name
then just click ok.
( c ) Binding the controls: By binding we mean,
10
telling a control what data it is supposed to
display.
(i) Binding the Employee Name text Box:
select the text box and go to properties and 9
click on “Data Binding” select tag
And then click on
First Name.

In the similar way, Bind the second text Box to “Phone”


Bind ListBox Control to “EmployeeID”
Set the DataGrid DataSource property to “mySet.Employees”
Amjad Mehmood
Lec.IIT 179
• Double the form and add the following code.
• sqlDataAdapter1.Fill(this.mySet,0,0,"Employees");
• Explanation: Fill method is used to fill the specified dataset (Ist
argument) with data. The second argument specify where to start
filling, the third argument specify how many records to retrieve
and the last is just a table that will be created in the specified
dataset to hold the data.
• sqlDataAdapter1.Fill(dataSet11,0,0,"authors");
• dataGrid1.DataSource=dataSet11.authors;

Amjad Mehmood
Lec.IIT 180
The Command Classes

• There are three Command classes: SqlCommand,


OleDbCommand, and OdbcCommand. You use a Command
object to run a SQL statement, such as a SELECT, INSERT,
UPDATE, or DELETE statement.
• You can also use a Command object
• to call a stored procedure
– retrieve rows from a specific table. You run the command stored in a
Command object using a Connection object

Amjad Mehmood
Lec.IIT 181
Coding
• class Class1
• {
• /// <summary>
• /// The main entry point for the application.
• /// </summary>
• [STAThread]
• static void Main(string[] args)
• {

• string source = "server=File_Server;" +
• "uid=sa;pwd=;" +
• "database=northwind" ;

• string select = "SELECT CustomerID,CompanyName,ContactName FROM Customers" ;

• SqlConnection conn = new SqlConnection( source ) ;

• SqlDataAdapter da = new SqlDataAdapter ( select , conn ) ;

• DataSet ds = new DataSet() ;


• da.Fill ( ds , "Customers") ;

• foreach ( DataRow row in ds.Tables["Customers"].Rows )


• Console.WriteLine ( "'{0}' from {1} {2}" , row[0] , row[1],row[2]) ;

• Console.ReadLine();

• }
• }
Amjad Mehmood
• }
Lec.IIT 182
• /*
• SelectIntoDataSet.cs
• illustrates how to perform a SELECT statement
• and store the returned rows in a DataSet object
• */

• using System;
• using System.Data;
• using System.Data.SqlClient;

• class SelectIntoDataSet
• {
• public static void Main()
• {
• // step 1: formulate a string containing the details of the
• // database connection
• string connectionString
• ="server=kust;database=Northwind;uid=sa;pwd=sa";

• // step 2: create a SqlConnection object to connect to the


• // database, passing the connection string to the constructor SqlConnection
mySqlConnection =new
Amjad Mehmood
• SqlConnection(connectionString); Lec.IIT 183
• // step 3: formulate a SELECT statement to retrieve the
• // CustomerID, CompanyName, ContactName, and Address
• // columns for the first ten rows from the Customers table
• string selectString ="SELECT TOP 10 CustomerID, CompanyName,
• ContactName, Address "+
• "FROM Customers " +
• "ORDER BY CustomerID";

• // step 4: create a SqlCommand object to hold the SELECT statement


• SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

• // step 5: set the CommandText property of the SqlCommand object to


• // the SELECT string
• mySqlCommand.CommandText = selectString;

• // step 6: create a SqlDataAdapter object


• SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();

• // step 7: set the SelectCommand property of the SqlAdapter object


• // to the SqlCommand object
• mySqlDataAdapter.SelectCommand = mySqlCommand;
• // step 8: create a DataSet object to store the results of
• // the SELECT statement
• DataSet myDataSet = new DataSet();
Amjad Mehmood

Lec.IIT 184
• / / step 9: open the database connection using the
• // Open() method of the SqlConnection object
• mySqlConnection.Open();

• // step 10: use the Fill() method of the SqlDataAdapter object to


• // retrieve the rows from the table, storing the rows locally
• // in a DataTable of the DataSet object
• Console.WriteLine("Retrieving rows from the Customers table");
• mySqlDataAdapter.Fill(myDataSet,"Customers");

• // step 11: close the database connection using the Close() method
• // of the SqlConnection object created in Step 1
• mySqlConnection.Close();

• // step 12: get the DataTable object from the DataSet object
• DataTable myDataTable = myDataSet.Tables["Customers"];

Amjad Mehmood
Lec.IIT 185
• // step 13: display the columns for each row in the DataTable,
• // using a DataRow object to access each row in the DataTable
• foreach (DataRow myDataRowmyDataTable.Rows)
• {Console.WriteLine("CustomerID = "+
myDataRow["CustomerID"]);
• Console.WriteLine("CompanyName = "+
myDataRow["CompanyName"]);
• Console.WriteLine("ContactName = "+
myDataRow["ContactName"]);
• Console.WriteLine("Address = "+
myDataRow["Address"]);
• }
• }

• }

Amjad Mehmood
Lec.IIT 186
Introduction to DataForm

Amjad Mehmood
Lec.IIT 187
MYSQLCONNECTION.CS
/* MySqlConnection.cs illustrates how to use a SqlConnection object to connect to a SQL Server
database */

using System;
using System.Data;
using System.Data.SqlClient;

class MySqlConnection
{
public static void Main()
{
// formulate a string containing the details of the // database
connection string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa";
// create a SqlConnection object to connect to the
// database, passing the connection string to the constructor

SqlConnection mySqlConnection = new SqlConnection(connectionString);


Amjad Mehmood
Lec.IIT 188
• // open the database connection using the
• // Open() method of the SqlConnection object
• mySqlConnection.Open();
• // display the properties of the SqlConnection object
Console.WriteLine("mySqlConnection.ConnectionString = "+ mySqlConnection.ConnectionString);

• Console.WriteLine("mySqlConnection.ConnectionTimeout = "+
mySqlConnection.ConnectionTimeout);

• Console.WriteLine("mySqlConnection.Database = "+ mySqlConnection.Database);


• Console.WriteLine("mySqlConnection.DataSource = "+ mySqlConnection.DataSource);
• Console.WriteLine("mySqlConnection.PacketSize = "+ mySqlConnection.PacketSize);
• Console.WriteLine("mySqlConnection.ServerVersion = "+ mySqlConnection.ServerVersion);
• Console.WriteLine("mySqlConnection.State = "+ mySqlConnection.State);
• Console.WriteLine("mySqlConnection.WorkstationId = "+ mySqlConnection.WorkstationId);

• // close the database connection using the Close() method // of the SqlConnection object
mySqlConnection.Close();
• }
• }
Amjad Mehmood
Lec.IIT 189
The output from this program is as follows
• mySqlConnection.ConnectionString = server=localhost;database=Northwind;uid=sa;

• mySqlConnection.ConnectionTimeout = 15

• mySqlConnection.Database = Northwind

• mySqlConnection.DataSource = localhost

• mySqlConnection.PacketSize = 8192

• mySqlConnection.ServerVersion = 08.00.0194

• mySqlConnection.State = Open

• mySqlConnection.WorkstationId = JMPRICE-DT1

Amjad Mehmood
Lec.IIT 190
CONNECTIONPOOLING.CS
• /* ConnectionPooling.cs illustrates connection pooling */ using System;
• using System.Data;
• using System.Data.SqlClient;

• class ConnectionPooling
• {
• public static void Main()
• {
• // create a SqlConnection object to connect to the database,
• // setting max pool size to 10 and min pool size to 5 SqlConnection mySqlConnection = new
SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa;" + "max pool size=10;min pool size=5" );
• // open the SqlConnection object 10 times

• for (int count = 1; count <= 10; count++)


• {
• Console.WriteLine("count = "+ count);
• // create a DateTime object and set it to the
• // current date and time
• DateTime start = DateTime.Now;

Amjad Mehmood
Lec.IIT 191
CONNECTIONPOOLING.CS
• // open the database connection using the
• // Open() method of the SqlConnection object

• mySqlConnection.Open();
• // subtract the current date and time from the start,
• // storing the difference in a TimeSpan

• TimeSpan timeTaken = DateTime.Now - start;

• // display the number of milliseconds taken to open


• // the connection

• Console.WriteLine("Milliseconds = "+ timeTaken.Milliseconds);

• // display the connection state

• Console.WriteLine("mySqlConnection.State = "+ mySqlConnection.State);

• // close the database connection using the Close() method


• // of the SqlConnection object

• mySqlConnection.Close();
• }
• }
Amjad Mehmood
• } Lec.IIT 192
The output from this program is as follows
• count = 1 Milliseconds = 101
• mySqlConnection.State = Open
• count = 2
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 3
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 4
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 5
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 6
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 7
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 8 Milliseconds = 0
• mySqlConnection.State = Open
• count = 9
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 10
• Milliseconds = 0
• mySqlConnection.State = Open

Amjad Mehmood
Lec.IIT 193
• Use the GetOrdinal() method of the DataReader object

• using System;
• using System.Data;
• using System.Data.SqlClient;
• class UsingColumnOrdinals
• {
• public static void Main()
• {
• SqlConnection mySqlConnection = new
SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );

• SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

• mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice, " + "UnitsInStock,


Discontinued " + "FROM Products " + "ORDER BY ProductID";

• mySqlConnection.Open();

• SqlDataReader productsSqlDataReader = mySqlCommand.ExecuteReader();

• // use the GetOrdinal() method of the DataReader object


Amjad Mehmood
• // to obtain the numeric positions of the columns Lec.IIT 194
• int productIDColPos =
productsSqlDataReader.GetOrdinal("ProductID");

• int productNameColPos =
productsSqlDataReader.GetOrdinal("ProductName");

• int unitPriceColPos = productsSqlDataReader.GetOrdinal("UnitPrice");

• int unitsInStockColPos =
productsSqlDataReader.GetOrdinal("UnitsInStock");

• int discontinuedColPos =
productsSqlDataReader.GetOrdinal("Discontinued");

Amjad Mehmood
Lec.IIT 195
Reading Rows from a SqlDataReader Object

• You read the rows from a DataReader object using the Read() method. This method returns the
Boolean true value when there is another row to read, otherwise it returns false.

• Let's take a look at two code snippets that illustrate these two ways of reading column values. The
first code snippet uses the column names to read the column values:

• while (productsSqlDataReader.Read()) { Console.WriteLine(productsSqlDataReader["ProductID"]);


Console.WriteLine(productsSqlDataReader["ProductName"]);
Console.WriteLine(productsSqlDataReader["UnitPrice"]);
Console.WriteLine(productsSqlDataReader["Discontinued"]); }

• The second code snippet uses the numeric column positions to read the column values:

• while (productsSqlDataReader.Read()) { Console.WriteLine(productsSqlDataReader[0]);


Console.WriteLine(productsSqlDataReader[1]); Console.WriteLine(productsSqlDataReader[2]);
Console.WriteLine(productsSqlDataReader[3]); }

Amjad Mehmood
Lec.IIT 196
• while (productsSqlDataReader.Read())
• {
• Console.WriteLine("ProductID = " + productsSqlDataReader[productIDColPos]);

• Console.WriteLine("ProductName = " + productsSqlDataReader[productNameColPos]);

• Console.WriteLine("UnitPrice = " + productsSqlDataReader[unitPriceColPos]);

• Console.WriteLine("UnitsInStock = " + productsSqlDataReader[unitsInStockColPos]);

• Console.WriteLine("Discontinued = " + productsSqlDataReader[discontinuedColPos]);


• }
• productsSqlDataReader.Close();
• mySqlConnection.Close();
• }
• }

Amjad Mehmood
Lec.IIT 197
• while (productsSqlDataReader.Read())
• {
• int productID = productsSqlDataReader.GetInt32(productIDColPos);
Console.WriteLine("productID = " + productID);

• string productName = productsSqlDataReader.GetString(productNameColPos);


Console.WriteLine("productName = " + productName);
• decimal unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos);
Console.WriteLine("unitPrice = " + unitPrice);

• short unitsInStock = productsSqlDataReader.GetInt16(unitsInStockColPos);


Console.WriteLine("unitsInStock = " + unitsInStock);

• bool discontinued = productsSqlDataReader.GetBoolean(discontinuedColPos);


Console.WriteLine("discontinued = " + discontinued);
• }

Amjad Mehmood
Lec.IIT 198
• Boxing and UnBoxing
• while (productsSqlDataReader.Read())
• {
• object productID = productsSqlDataReader[productIDColPos];

• object productName = productsSqlDataReader[productNameColPos];

• object unitPrice = productsSqlDataReader[unitPriceColPos];

• object unitsInStock = productsSqlDataReader[unitsInStockColPos];

• object discontinued = productsSqlDataReader[discontinuedColPos];

• Console.WriteLine("productID = " + productID); Console.WriteLine("productName = " +


productName); Console.WriteLine("unitPrice = " + unitPrice); Console.WriteLine("unitsInStock
= " + unitsInStock); Console.WriteLine("discontinued = " + discontinued);
• }

• If U want to use it further

• decimal newUnitPrice = (decimal) unitPrice * 1.2m;

Amjad Mehmood
Lec.IIT 199
Reading Null Values
• you'll get the following exception:
• System.Data.SqlTypes.SqlNullValueException
• You can check if a column contains a null value using the IsDBNull()
method of a DataReader object.
• This method returns a Boolean true or false value that indicates
whether the column value is null.
• You can then use that Boolean result to decide what to do. For
example:

Amjad Mehmood
Lec.IIT 200
• if (productsSqlDataReader.IsDBNull(unitPriceColPos))

• {
• Console.WriteLine("UnitPrice column contains a null value");
• }

else

• {
• unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos);
• }

Amjad Mehmood
Lec.IIT 201
• /*

• ExecuteMultipleSelects.cs illustrates how to execute


• multiple SELECT statements using a SqlCommand object
• and read the results using a SqlDataReader object
• */

• using System;
• using System.Data;
• using System.Data.SqlClient;

• class ExecuteSelect
• {
• public static void Main()
• {
• SqlConnection mySqlConnection =new SqlConnection(
• "server=localhost;database=Northwind;uid=sa;pwd=sa");

• SqlCommand mySqlCommand =
• mySqlConnection.CreateCommand();
Amjad Mehmood
Lec.IIT 202

• // set the CommandText property of the SqlCommand object to


• // the mutliple SELECT statements
• mySqlCommand.CommandText =
• "SELECT TOP 5 ProductID, ProductName " +
• "FROM Products " +
• "ORDER BY ProductID;" +
• "SELECT TOP 3 CustomerID, CompanyName "+

"FROM Customers " +


• "ORDER BY CustomerID;" +
• "SELECT TOP 6 OrderID, CustomerID " +
• "FROM Orders " +
• "ORDER BY OrderID;";

• Amjad Mehmood
Lec.IIT 203
• mySqlConnection.Open();

• SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();


• // read the result sets from the SqlDataReader object using
• // the Read() and NextResult() methods
• do
• {
• while (mySqlDataReader.Read())
• {
• Console.WriteLine("mySqlDataReader[0] = " +
• mySqlDataReader[0]);
• Console.WriteLine("mySqlDataReader[1] = " +
• mySqlDataReader[1]);
• }
• Console.WriteLine(""); // visually split the results
• } while (mySqlDataReader.NextResult());

• mySqlDataReader.Close();
• mySqlConnection.Close();
• }
• } Amjad Mehmood
Lec.IIT 204
POPULATEDATASETUSINGSELECT.CS

• using System; using System.Data;


• using System.Data.SqlClient;
• class PopulateDataSetUsingSelect
• {
• public static void Main()
• {
• SqlConnection mySqlConnection = new
SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
• // create a SqlCommand object and set its CommandText property
• // to a SELECT statement that retrieves the top 5 rows from
• // the Products table
• SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice "
+ "FROM Products " + "ORDER BY ProductID";

Amjad Mehmood
Lec.IIT 205
// create a SqlDataAdapter object and set its SelectCommand
// property to the SqlCommand object
• SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand =
mySqlCommand;
// create a DataSet object
• DataSet myDataSet = new DataSet();
• // open the database connection mySqlConnection.Open(); // use the Fill() method of the SqlDataAdapter
object to
• // retrieve the rows from the table, storing the rows locally // in a DataTable of the DataSet object
Console.WriteLine("Retrieving rows from the Products table");
• int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Products");
• Console.WriteLine("numberOfRows = " + numberOfRows);
• // close the database connection
• mySqlConnection.Close();
• // get the DataTable object from the DataSet object
• DataTable myDataTable = myDataSet.Tables["Products"];
• // display the column values for each row in the DataTable,
• // using a DataRow object to access each row in the DataTable
• foreach (DataRow myDataRow in myDataTable.Rows)
• {
• Console.WriteLine("ProductID = " + myDataRow["ProductID"]); Console.WriteLine("ProductName = " +
myDataRow["ProductName"]); Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);
• }
• }
• } Amjad Mehmood
Lec.IIT 206
• /*
• PopulateDataSetUsingRange.cs illustrates how to populate a DataSet
• object with a range of rows from a SELECT statement
• */

• using System;
• using System.Data;
• using System.Data.SqlClient;

• class PopulateDataSetUsingRange
• {
• public static void Main()
• {
• SqlConnection mySqlConnection =
• new SqlConnection(
• "server=kust;database=Northwind;uid=sa;pwd=sa"
• );
• // create a SqlCommand object and set its CommandText property
• // to a SELECT statement that retrieves the top 5 rows from
• // the Products table
• SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
• mySqlCommand.CommandText =
• "SELECT TOP 5 ProductID, ProductName, UnitPrice " +
• "FROM Products " +
• "ORDER BY ProductID";

Amjad Mehmood
Lec.IIT 207
• SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
• mySqlDataAdapter.SelectCommand = mySqlCommand;
• DataSet myDataSet = new DataSet();
• mySqlConnection.Open();
• // use the Fill() method of the SqlDataAdapter object to
• // retrieve the rows from the table, storing a range of rows
• // in a DataTable of the DataSet object
• Console.WriteLine("Retrieving rows from the Products table");
• int numberOfRows = mySqlDataAdapter.Fill(myDataSet, 1, 3, "Products");
Console.WriteLine("numberOfRows = " + numberOfRows); mySqlConnection.Close();
• DataTable myDataTable = myDataSet.Tables["Products"];
• foreach (DataRow myDataRow in myDataTable.Rows)
• {
• Console.WriteLine("ProductID = " + myDataRow["ProductID"]);
Console.WriteLine("ProductName = " + myDataRow["ProductName"]);
Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);
• }
• }
• }

Amjad Mehmood
Lec.IIT 208
• /*
• PopulateDataSetUsingProcedure.cs illustrates how to populate a
• DataSet object using a stored procedure
• */

• using System;
• using System.Data;
• using System.Data.SqlClient;

• class PopulateDataSetUsingProcedure
• {
• public static void Main()
• {
• SqlConnection mySqlConnection =
• new SqlConnection(
• "server=kust;database=Northwind;uid=sa;pwd=sa"
• );

• // create a SqlCommand object and set its CommandText property


• // to call the CustOrderHist() stored procedure
• SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
• mySqlCommand.CommandText =
• "EXECUTE CustOrderHist @CustomerID";
Amjad Mehmood
• } Lec.IIT 209
• mySqlCommand.Parameters.Add(
• "@CustomerID", SqlDbType.NVarChar, 5).Value = "ALFKI";

• SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();


• mySqlDataAdapter.SelectCommand = mySqlCommand;
• DataSet myDataSet = new DataSet();
• mySqlConnection.Open();
• Console.WriteLine("Retrieving rows from the CustOrderHist() Procedure");
• int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "CustOrderHist");
• Console.WriteLine("numberOfRows = " + numberOfRows);
• mySqlConnection.Close();

• DataTable myDataTable = myDataSet.Tables["CustOrderHist"];


• foreach (DataRow myDataRow in myDataTable.Rows)
• {
• Console.WriteLine("ProductName = " + myDataRow["ProductName"]);
• Console.WriteLine("Total = " + myDataRow["Total"]);
• }
• Console.Read();
• }

Amjad Mehmood
Lec.IIT 210

You might also like