You are on page 1of 184

1

C#

.1 : C# C# Namespace
....
.2 :
....
.3 - : if switch break
goto ....
.4 - : - - while - do while
for foreach ....
.5 :
this ....
: Namespaces .6 - Namespace - using - alias
Namespace ....
.7 : ....

.8 :

.9 : Polymorphism Override
....
.10 ) : (Properties property property
....
.11 ) : (Indexer
....
.12 ) : (Structures
....
.13 ) : (Interfaces interface
....
.14 ) (Event : delegate delegate delegate
....
: Handling Exception .15 try/catch
.... finally
.16 ) : (Attribute
....
.17 ) : (Enum
....
Overload .18 : Overload .
.19 ) : (1 .
.

: C#

C# . :

C#
Namespace
)(Class
)(Main
/ I/O

1-1 Welcome C#
// Namespace
;using System

//
class WelcomeCSS
{
//
)(public static void Main
{
//
;)"!Console.WriteLine("Welcome to the C# Persian Tutorial
}
}
1-1 4 Namespace )( Main .C#
C# .
Command Line Visual . Command Line

DOS . Visual
. Microsoft C#
Command Line Compiler Command Line Microsoft Visual C# Visual
. .
Visual C# Visual Studio.Net .
Visual Studio.Net . C# Console
.
Visual Studio.Net
.
Run Command
Line csc Welcome.cs :
) (Executable Welcome.exe .

: ) Visual Studio.Net(VS.Net
.
:
;)(Console.ReadLine


Enter .

C# Case Sensitive
ReadLine readLine C#
.

Namespace System .
WriteLine ReadLine System .
/ . using System
System . using System
)( System.Console.WriteLine )( Console.WriteLine .

Class Welcome CSS )( .


C# ) (Object ) (Interfaces ) (Structures.
. .
) (Behavior .

. )( Main
C# . )( Main
. )( Main dll
.
)( Main static . Modifier . static
)( Main ) (Instance
. static )( Main
)( Main ) .
) (OOP .
(.

void
.
.
.

)( Main )( Console.WriteLine Console . System


)( WriteLine .Console C# ") ". (dot
. )( WriteLine Console " ".
.

C# // .
. //
.

* / */ . /* */
) (Comments .

) (Statements ";" . { } .
} { .

. )( Main
. 1-2 .
)( Main .

: 1-2 )( Main .
// Namespace
;using System
//
class NamedWelcome
{
//
)public static void Main(string[] args
{
//
;)]Console.WriteLine("Hello, {0}!", args[0
;)"!Console.WriteLine("Welcome to the C# Persian Tutorial
}
}
Command-Line
Command-Line . .

1-2 )( Main args .


. )][ (string .) (types
. [] .
.

)( Console.WriteLine
. )( Console.WriteLine } {0 .
] args[0 . " "
} {0 " . ]args[0
. ][ . C#
).
C#(!.

} {0 . ] args[0.
Command-Line :
!>Hello!, Meysam
!>Welcome to C# Persian Tutorial
Command-Line .
} {n n . n
. :
;)]Console.WriteLine("Hello! ,{0} ,{1}, {2}",args[0],args[1],args[2
] args[0],args[1],args[2 . 3
} {n .
.

1-2 Command-Line
Command-Line Command-Line
. .

: 1-3 .
// Namespace
;using System

//
class InteractiveWelcome
{
//
)(public static void Main
{
//
;)" Console.Write("What is your name?:
//
;))(Console.Write("Hello, {0}! ", Console.ReadLine
;)"!Console.WriteLine("Welcome to the C# Persian Tutorial
}
}
)( Main . 1-2 .
. Hello,
.
. .
.
} {0 )( Console.ReadLine
. )( ReadLine Console .
:

What is your name?:


) (
) Enter (.
!Hello, Meysam
) (
!Welcome to the C# Persian Tutorial

:
What is your name?:
!Hello, Meysam! Welcome to the C# Persian Tutorial
)( ReadLine . } {0
. :
;)(string myName=Console.ReadLine
;)Console.WriteLine("Hello, {0}!",myName

myName
} {0 .

C# . C#
. )( Main .
C# . System Console
)( WriteLine )( ReadLine.
. mail.

10

C#
C# . :

) (Types C#
) (Expressions C#
) (String C#
) (Arrays C#
.

C# .
.
C#
. ).
(
C# : ) (Boolean ) (integer (Floating
) points ) (Decimal). Boolean
) (True ) (False(.
1 )(Boolean
;using System
class Booleans
{
)(public static void Main
{
;bool content = true
;bool noContent = false
Console.WriteLine("It is {0} that C# Persian provides C# programming language
;)content.", content
;)Console.WriteLine("The statement above is not {0}.", noContent
}
}
Boolean . bool
true false C
C++
true false bool integer .
C# bool true false . :
It is True that C# Persian provides C# programming language content.

11

The statement above is not False.


C# .

-128 127

sbyte

0 255

byte

-32768 32767

16

short

0 65535

16

ushort

-2147483648 2147483647

32

int

0 4294967295

32

uint

-9223372036854775808 9223372036854775807

64

long

0 18446744073709551615

64

ulong

. char.

C# char 65535 16
.
.
C# .

32

float

16-15

64

double

29-28

128

decimal

floating point .
decimal . C#
Java .
.
). expression statement
(. C#
.

)(

12

(x) x.y f(x) a[x] x++ x-new typeof sizeof checked


unchecked
+ - ! ~ ++x --x (T)x

* / %

+ -

>> <<

< > <= >= is

=! ==

&
|

AND
OR

XOR

&&

AND

||

OR

?:

=& =>> =<< == *= /= %= += -


=| =^

.
.
.
-2 )(Unary
;using System
class Unary
{
)(public static void Main
{
;int unary = 0
;int preIncrement
;int preDecrement
;int postIncrement
;int postDecrement
;int positive
;int negative
;sbyte bitNot
;bool logNot
;preIncrement = ++unary
;)Console.WriteLine("Pre-Increment: {0}", preIncrement

13

;preDecrement = --unary
;)Console.WriteLine("Pre-Decrement: {0}", preDecrement
;postDecrement = unary--
;)Console.WriteLine("Post-Decrement: {0}", postDecrement
;postIncrement = unary++
;)Console.WriteLine("Post-Increment: {0}", postIncrement
;)Console.WriteLine("Final Value of Unary: {0}", unary
;positive = -postIncrement
;)Console.WriteLine("Positive: {0}", positive
;negative = +postIncrement
;)Console.WriteLine("Negative: {0}", negative
;bitNot = 0
;)bitNot = (sbyte)(~bitNot
;)Console.WriteLine("Bitwise Not: {0}", bitNot
;logNot = false
;logNot = !logNot
;)Console.WriteLine("Logical Not: {0}", logNot
}
}
x++ ) x x ++
post-increment (post-decrement ) (operand
. ++
. x++ x=x+1 x+=1
) ++ (--
. x=y++ x=0 y=1
x 1 y y
x=++y y
x x 2). (.
++x x
.
2 unary 0 . ++x
unary 1 1 preIncrement
. x unary 0 preDecrement
.
x-- unary postDecrement
unary -1 . x++
unary -1 postIncrement unary
) 0( .

14

bitNot . )~( ) (
bitNot .
. 00000000
11111111 .
) (sbyte)(~bitNot . byte unshort short sbyte
int . bitNot
(Type) operator Type operator
. bitNot
sbyte ) (
. ) (Type Casting

. int ) 32( 8) sbyte(
Casting .
) sbyte (int Casting
. ) (Signed ) (Unsigned
. .

).
(.
"!"
Boolean true false . ) (2 logNot
"!" false true . 2
:
Pre-Increment: 1
Pre-Decrement 0
Post-Decrement: 0
Post-Increment -1
Final Value of Unary: 0
Positive: 1
Negative: -1
Bitwise Not: -1
Logical Not: True

3
;using System
class Binary
{
)(public static void Main

15

{
;int x, y, result
;float floatResult
;x = 7
;y = 5
;result = x+y
;)Console.WriteLine("x+y: {0}", result
;result = x-y
;)Console.WriteLine("x-y: {0}", result
;result = x*y
;)Console.WriteLine("x*y: {0}", result
;result = x/y
;)Console.WriteLine("x/y: {0}", result
;floatResult = (float)x/(float)y
;)Console.WriteLine("x/y: {0}", floatResult
;result = x%y
;)Console.WriteLine("x%y: {0}", result
;result += x
;)Console.WriteLine("result+=x: {0}", result
}
}
:
x+y: 12
x-y: 2
x*y: 35
x/y: 1
x/y: 1.4
x%y: 2
result+=x: 9
3 ).
" .("+
. " "+ " "- "*"
" "/ .
floatResult float . Casting
x y int float .
" "% . .
.

16

result+=x .
. = result
result+x . result x result .
) (string .
" " . " ."Hi This is a string type

" " . .
;string Name

;"Name = "My name is Meysam


Name

.
). )( Console.ReadLine (.

.

)(Arrays
C# ) (Arrays .

. .

-4
;using System
class Array
{
)(public static void Main
{
;} int[] myInts = { 5, 10, 15
;][]bool[][] myBools = new bool[2
;]myBools[0] = new bool[2
;]myBools[1] = new bool[1
;]double[,] myDoubles = new double[2, 2
;]string[] myStrings = new string[3
Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", myInts[0],
;)]myInts[1], myInts[2
;myBools[0][0] = true

17

;myBools[0][1] = false
;myBools[1][0] = true
Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0],
;)]myBools[1][0
;myDoubles[0, 0] = 3.147
;myDoubles[0, 1] = 7.157
;myDoubles[1, 1] = 2.117
;myDoubles[1, 0] = 56.00138917
Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0],
;)]myDoubles[1, 0
;"myStrings[0] = "Joe
;"myStrings[1] = "Matt
;"myStrings[2] = "Robert
Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}",
;)]myStrings[0], myStrings[1], myStrings[2
}
}
4 :
myInts[0]: 5, myInts[1]: 10, myInts[2]: 15
myBools[0][0]: True, myBools[1][0]: True
myDoubles[0, 0]: 3.147, myDoubles[1, 0]: 56.00138917
myStrings[0]: Joe, myStrings[1]: Matt, myStrings[2]: Robert
.
.
myInts int 3
} { .
:
;type[] arrayName
type arrayName .
.
.
} { . } {
} { .
4 3 10 5 15.
.
;]type[] arrayName = new type[n
new n .
.
. .
;]int[] myArray = new int[15
www.Arsanjan.blogfa.com

18

int 15 . 15 int
.
) (Multi Dimensional Arrays
.
:
;]type[ , , , ] arrayName = new type[n1, n2, . , nm
n1 nm .
:
;]char[ , , ] charArray = new char[3,5,7
char 5 3 7 .
) (Jagged Arrays . C#
.
.
. .
.

31 . 6 31 6
.
12
:
:
;]int[ , ] monthArray = new int[12,31
:
;][]int[][] monthArray = new int[12

12 31 . .
12


.
:
;]monthArray[1] = new int[31
;]monthArray[10] = new int [30
.
.

www.Arsanjan.blogfa.com

19

.
. C# C C++
.
10 9.
. .
] monthArray[3,7 3 7 ).
] intArray[12 12
12 (.
12

11

10

5
.
string .
C C
. C#
C
.
C

C# .
}"string[] stringArray = {"My name is Meysam", "This is C# Persian Blog
..
;)]Console.WriteLine("{0}",stringArray[0
..

.
:
My name is Meysam
. C#
.
C#
.
C#
. .
www.Arsanjan.blogfa.com

20

C# .

.

www.Arsanjan.blogfa.com

21

if if if-else else...else if-else...if switch break


case goto AND OR


C# . :

if

switch

break switch

goto

if

.
. .
if . :
.

3-1 if
;using System
class IfSelect
{
)(public static void Main
{
;string myInput
;int myInt
;)" Console.Write("Please enter a number:
;)(myInput = Console.ReadLine
;)myInt = Int32.Parse(myInput
//
)if (myInt > 0
{
www.Arsanjan.blogfa.com

22

Console.WriteLine("Your number {0} is greater than zero.", myInt);


}
//
if (myInt < 0)
Console.WriteLine("Your number {0} is less than zero.", myInt);
//
if (myInt != 0)
{
Console.WriteLine("Your number {0} is not equal to zero.", myInt);
}
else
{
Console.WriteLine("Your number {0} is equal to zero.", myInt);
}
//
if (myInt < 0 || myInt == 0)
{
Console.WriteLine("Your number {0} is less than or equal to zero.", myInt);
}
else if (myInt > 0 && myInt <= 10)
{
Console.WriteLine("Your number {0} is between 1 and 10.", myInt);
}
else if (myInt > 10 && myInt <= 20)
{
Console.WriteLine("Your number {0} is between 11 and 20.", myInt);
}
else if (myInt > 20 && myInt <= 30)
{
Console.WriteLine("Your number {0} is between 21 and 30.", myInt);
}
else
{
Console.WriteLine("Your number {0} is greater than 30.", myInt);
}
} //Main()
} //IfSelect
myInt 3-1
Please . if
Console.ReadLine() . enter a umber:
Console.ReadLine() . Enter
www.Arsanjan.blogfa.com

23

myInput
.
. myInput
. )( Int32.Parse .
.
myInput myInt int
. myInt ) .
Int32 (.
if .

if
} if (boolean expression) {statements . if
if . .
/ . if
. true )
}{ (.
false if . if
) if(myInt > 0 . myInt if
if .
if if
. if
. .

if-else
.
true . if
. if true if
else . " if
if else ".
if-else :

)if (boolean expression


}{statements

else
}{statements
boolean expression statements
.
www.Arsanjan.blogfa.com

24

if-else if else if

. if if ) (Nested If
if . if 3-1 if
. if . true
. false .
else if .
true .
if true .
if :

)if (boolean expression


}{statements
)else if (boolean expression
}{statements

else
}{statements

OR ||) AND &&(


if .
|| OR . OR true
true . ) (myInt < 0 || myInt == 0
myInt true .
C# OR . OR ||
OR | . OR OR
OR false
.
) (myInt > 0 && myInt <= 10 AND )&&( .
true AND true . myInt
10 true . AND OR . AND
)&( AND )&&( . AND )&(
AND )&&(
true . )|| &&( ) (short-circuit
.

switch
www.Arsanjan.blogfa.com

25

. switch if

switch 3-2
using System;
class SwitchSelect
{
public static void Main()
{
string myInput;
int myInt;
begin:
Console.Write("Please enter a number between 1 and 3: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
// switch
switch (myInt)
{
case 1:
Console.WriteLine("Your
break;
case 2:
Console.WriteLine("Your
break;
case 3:
Console.WriteLine("Your
break;
default:
Console.WriteLine("Your
break;
} //switch

number is {0}.", myInt);

number is {0}.", myInt);

number is {0}.", myInt);

number {0} is not between 1 and 3.", myInt);

decide:
Console.Write("Type \"continue\" to go on or \"quit\" to stop: ");
myInput = Console.ReadLine();
// switch
switch (myInput)
{
case "continue":
goto begin;
case "quit":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("Your input {0} is incorrect.", myInput);
www.Arsanjan.blogfa.com

26

;goto decide
} //switch
)(} //Main
} //SwitchSelect
3-2 switch . switch switch
switch . switch short, ,sbyte, byte :
). ushort, int, uint, long, ulong, char, string, enum enum
(. switch 3-2 switch ) (int.
switch switch
switch . case .
case " ": .
switch . switch int . switch
switch switch
. myInt .
switch .
case " ": . :
case 1:
;)Console.WriteLine("Your number is {0}.", myInt
1 )( Console.WriteLine . myInt
1 case 1 Console.WriteLine("Your number is {0}.",
;) myInt . switch case switch
break switch .
switch case break
. default switch
switch . switch case
default . switch .
break default .
case switch break
. . case
goto .

www.Arsanjan.blogfa.com

27

case case
. .
)switch (myInt
{
case 1:
case 2:
case 3:
;)Console.WriteLine("Your number is {0}.", myInt
;break
default:
;)Console.WriteLine("Your number {0} is not between 1 and 3.", myInt
;break
}
case .
2 1 3 ;) Console.WriteLine("Your number is {0}.",
myInt . myInt 2 1 3 .
switch case
case .
switch 3-2 . switch
goto . goto ) (label .
continue switch .
case goto
begin: ) )( .(Main
switch begin: .
goto quit
.
continue quit switch default
goto decide .
decide ).
continue (quit .
goto switch goto
) (Debug .
goto .

www.Arsanjan.blogfa.com

28

goto .
.
switch if-else
. .
)switch(myChar
{
case 'A' :
;)"Console.WriteLine("Add operation\n
;break
case 'M' :
;)"Console.WriteLine("Multiple operation\n
;break
case 'S' :
;)"Console.WriteLine("Subtraction operation\n
;break
default :
;)"Console.WriteLine("Error, Unknown operation\n
;break
}
switch if-else
)'if (myChar == 'A
;)"Console.WriteLine("Add operation\n
)'else if (myChar == 'M
;)"Console.WriteLine("Multiple operation\n
)'else if (myChar == 'S
;)"Console.WriteLine("Subtraction operation\n
else
;)"Console.WriteLine("Error, Unknown operation\n
switch if-else .
if switch . goto
. goto
.

www.Arsanjan.blogfa.com

29


C# .
:
 while
 do-while
 for
 foreach
 break
 continue
goto .
. C# .
while.
while
.
;using System
class WhileLoop
{
)(public static void Main
{
;int myInt = 0
)while (myInt < 10
{
;)Console.Write("{0} ", myInt
;myInt++
}
;)(Console.WriteLine
}
}

4-1 while . while


.
true
.false myInt 10 .
true
.

www.Arsanjan.blogfa.com

30

myInt while
true while .
while false . while
9 .
.
. do-while while
do-while
. 4-2
using System;
class DoLoop
{
public static void Main()
{
string myChoice;
do
{
//
Console.WriteLine("My Address Book\n");
Console.WriteLine("A - Add New Address");
Console.WriteLine("D - Delete Address");
Console.WriteLine("M - Modify Address");
Console.WriteLine("V - View Addresses");
Console.WriteLine("Q - Quit\n");
Console.WriteLine("Choice (A,D,M,V,or Q): ");
//
myChoice = Console.ReadLine();
//
switch(myChoice)
{
case "A":
case "a":
Console.WriteLine("You wish to add an address.");
break;
case "D":
case "d":
Console.WriteLine("You wish to delete an address.");
break;
case "M":
case "m":
Console.WriteLine("You wish to modify an address.");
break;
case "V":

www.Arsanjan.blogfa.com

31

case "v":
;)"Console.WriteLine("You wish to view the address list.
;break
case "Q":
case "q":
;)"Console.WriteLine("Bye.
;break
default:
;)Console.WriteLine("{0} is not a valid choice", myChoice
;break
}
;)"Console.Write("Press Enter key to continue...
;)(Console.ReadLine
;)(Console.WriteLine
;)"} while (myChoice != "Q" && myChoice != "q
}
}

4-2 do-while . :
do
;)>{ <statements> } while (<boolean expression
C# .
true false .
do while
do .
. while
.
4-2 . )( Main myChoice .
. .
)( Console.ReadLine
myChoice . .
switch . switch default
.
for
4-3 .
;using System
class ForLoop
{
)(public static void Main

www.Arsanjan.blogfa.com

32

{
)for (int i=0; i < 20; i++
{
)if (i == 10
;break
)if (i % 2 == 0
;continue
;)Console.Write("{0} ", i
}
;)(Console.WriteLine
}
}

4-3 for . for


. for :
)>(<initializer list>; <boolean expression>; <postloopaction list
initializer list .
for . 4-3
.
initializer list for (boolean
) expression .
true false .
.
true for . 4-3 if
for . if i 10 .
break . break
switch . break for for
.
if ) (% i 2 .
i 2 continue . continue for
continue for .
for postloopaction list . for
. for
. 4-3 .
true for
. for true .
www.Arsanjan.blogfa.com

33

foreach
4-4 .
;using System
class ForEachLoop
{
)(public static void Main
{
;}"string[] names = {"Meysam", "Ghazvini", "C#", "Persian
)foreach (string person in names
{
;)Console.WriteLine("{0} ", person
}
}
}

foreach . C# 4-4
. )( Main names
.
foreach in .
.
.
.
foreach .
foreach foreach true .
false foreach .
foreach .
4-4 person names .
names person foreach
)( Console.WriteLine .

: foreach
. .

do-while while for foreach . while


true
www.Arsanjan.blogfa.com

34

. do
true . for
foreach .
break continue .

www.Arsanjan.blogfa.com

35


C# . :

 ) (static methods )(instance



 this
)( Main .

.
.
:
} [attributes][ modifiers] return-type method-name ([ parameters] ) { statements
attributes modifiers return-type .
C# . .
method-name .
) (parameters
C#
. 5-1
.
;using System
class OneMethod
{
)(public static void Main
{
;string myChoice
;)(OneMethod om = new OneMethod
do
{
;)(myChoice = om.getChoice
//
)switch(myChoice
{
case "A":
case "a":

www.Arsanjan.blogfa.com

36

Console.WriteLine("You wish to add an address.");


break;
case "D":
case "d":
Console.WriteLine("You wish to delete an address.");
break;
case "M":
case "m":
Console.WriteLine("You wish to modify an address.");
break;
case "V":
case "v":
Console.WriteLine("You wish to view the address list.");
break;
case "Q":
case "q":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("{0} is not a valid choice", myChoice);
break;
}
//
Console.WriteLine();
Console.Write("Press Enter key to continue...");
Console.ReadLine();
Console.WriteLine();
} while (myChoice != "Q" && myChoice != "q");
//
}
string getChoice()
{
string myChoice;
//
Console.WriteLine("My Address Book\n");
Console.WriteLine("A - Add New Address");
Console.WriteLine("D - Delete Address");
Console.WriteLine("M - Modify Address");
Console.WriteLine("V - View Addresses");
Console.WriteLine("Q - Quit\n");
Console.Write("Choice (A,D,M,V,or Q): ");
//
myChoice = Console.ReadLine();
Console.WriteLine();
return myChoice;
}
}

www.Arsanjan.blogfa.com

37

5-1 4
)( Main )( getChoice .
. switch )( Main .
)( getChoice /
.
myChoice . myChoice
)( Main . ) (Local
. .
)( getChoice . return
myChoice )( Main .
return . .
C# . ) (Static ) .(Instance
static
. ) (Object .
static
. .
)( getChoice .
)( OneMethod om = new OneMethod .
om OneMethod . om
)( OneMethod .
)( OneMethod om . new
heap . )( OneMethod heap
om . )( OneMethod om om
.
" ". . )(getChoice
om . om.getChoice() :
)( getChoice "=" . )( getChoice
myChoice )( Main . .


5-2 .
;using System

www.Arsanjan.blogfa.com

38

class Address
{
public string name;
public string address;
}//Address
class MethodParams
{
public static void Main()
{
string myChoice;
MethodParams mp = new MethodParams();
do
{
//
myChoice = mp.getChoice();
//
mp.makeDecision(myChoice);
//
Console.Write("Press Enter key to continue...");
Console.ReadLine();
Console.WriteLine();
} while (myChoice != "Q" && myChoice != "q");
//
}//Main
//
string getChoice()
{
string myChoice;
//
Console.WriteLine("My Address Book\n");
Console.WriteLine("A - Add New Address");
Console.WriteLine("D - Delete Address");
Console.WriteLine("M - Modify Address");
Console.WriteLine("V - View Addresses");
Console.WriteLine("Q - Quit\n");
Console.WriteLine("Choice (A,D,M,V,or Q): ");
//
myChoice = Console.ReadLine();
return myChoice;
}//getChoice()
//
void makeDecision(string myChoice)
{
Address addr = new Address();

www.Arsanjan.blogfa.com

39

switch(myChoice)
{
case "A":
case "a":
addr.name = "Meysam";
addr.address = "C# Persian";
this.addAddress(ref addr);
break;
case "D":
case "d":
addr.name = "Ghazvini";
this.deleteAddress(addr.name);
break;
case "M":
case "m":
addr.name = "CSharp";
this.modifyAddress(out addr);
Console.WriteLine("Name is now {0}.", addr.name);
break;
case "V":
case "v":
this.viewAddresses("Meysam", "Ghazvini", "C#", "Persian");
break;
case "Q":
case "q":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("{0} is not a valid choice", myChoice);
break;
}
}
//
void addAddress(ref Address addr)
{
Console.WriteLine("Name: {0}, Address: {1} added.", addr.name,
addr.address);
}
//
void deleteAddress(string name)
{
Console.WriteLine("You wish to delete {0}'s address.", name);
}
//
void modifyAddress(out Address addr)
{
//Console.WriteLine("Name: {0}.", addr.name); //

www.Arsanjan.blogfa.com

40

;)(addr = new Address


;"addr.name = "Meysam
;"addr.address = "C# Persian
}
//
)void viewAddresses(params string[] names
{
)foreach (string name in names
{
;)Console.WriteLine("Name: {0}", name
}
}
}

5-2 5-1 .
C# params out ref : . value 5-2
Address .
)( Main )( getChoice
myChoice . myChoice )( makeDecision .
)( myDecision myChoice .
)( makeDecision .
modifier value .
) (value parameter ) (Stack .

.
switch )( makeDecision case .
)( Main . mp this .
this .
)( addAddress ref .
heap .
ref .
. ) (ref
/ .
out
.

www.Arsanjan.blogfa.com

41

) (Overhead .
.
)( modifyAddress out . out .


. )( modifyAddress .
.
.
out return .
C# params
. params (Jagged
) Array . )( makeDecision )( viewAddresses
params .
. )(viewAddresses
foreach . params
.

. C# .
out ref value . params value
.

www.Arsanjan.blogfa.com

42

Namespaces
:
 Namespace C#
 (using directive) using
 (alias directive) alias
 Namespace
; using System .
Namespace System .
using .
Namespace C# . Namespace
.
Namespace
.
// Namespace
;using System
// C# Persian Namespace
namespace csharp-persian
{
//
class NamespaceCSS
{
//
)(public static void Main
{
//
;)"Console.WriteLine("This is the new C# Persian Namespace.
}
}
}

6-1 Namespace . namespace


csharp-persian Namespace . Namespace 6-2 .
// Namespace
;using System
// C# Persian Namespace
namespace csharp-persian

www.Arsanjan.blogfa.com

43

{
namespace tutorial
{
//
class NamespaceCSS
{
//
)(public static void Main
{
//
;)"Console.WriteLine("This is the new C# Persian Namespace.
}
}
}
}

Namespace .
Namespace . Namespace
Namespace .
Namespace . 6-2
. Namespace .
// Namespace
;using System
// C# Persian Tutorial Namespace
namespace csharp-persian.tutorial
{
//
class NamespaceCSS
{
//
)(public static void Main
{
//
;)"Console.WriteLine("This is the new C# Persian Namespace.
}
}
}

6-3 Namespace .
Namespace " ". csharp-persian tutorial .
6-2 .
Namespace
www.Arsanjan.blogfa.com

44

// Namespace
using System;
namespace csharp-persian
{
// namespace
namespace tutorial
{
class myExample1
{
public static void myPrint1()
{
Console.WriteLine("First Example of calling another namespace member.");
}
}
}
//
class NamespaceCalling
{
//
public static void Main()
{
//
tutorial.myExample1.myPrint1();
tutorial.myExample2.myPrint2();
}
}
}
// Namespace Namespace
namespace csharp-persian.tutorial
{
class myExample2
{
public static void myPrint2()
{
Console.WriteLine("Second Example of calling another namespace member.");
}
}
}

Namespace 6-4 . Namespace 6-4


Main() . myPrint1 myExample1 csharp-persian tutorial
tutorial Main() . tutorial.myExample1.myPrint1
. csharp-persian Namespace
www.Arsanjan.blogfa.com

45

6-4 Namespace csharp-persian.tutorial .


myExamlpe1 myExample2 Namespace
Namespace . )( Main myPrint2
tutorial.myExample2.myPrint2 . myExample2
myPrint2 csharp-persian
Namespace csharp-persian.
myExample1 myExample2
Namespace . myPrint1 myPrint2
.
.
using
// Namespace
;using System
;using csharp_station.tutorial
//
class UsingDirective
{
//
)(public static void Main
{
// Namespace
;)(myExample.myPrint
}
}
// C# PersianTutorial Namespace
namespace csharp-persian.tutorial
{
class myExample
{
)(public static void myPrint
{
;)"Console.WriteLine("Example of using a using directive.
}
}
}

Namespace
using . 6-5 using . using
www.Arsanjan.blogfa.com

46

System .
System System . )(myPrint
Console System )( WriteLine . using
)( WriteLine )( System.Console.WriteLine
.
using csharp-persian.tutorial Namespace
. using )( myPrint
)( myExample.myPrint using
)( csharp-persian.tutorial.myExample.myPrint.
Alias
// Namespace
;using System
using csTut = csharp-persian.tutorial.myExample; // alias
//
class AliasDirective
{
//
)(public static void Main
{
// Namespace
;)(csTut.myPrint
;)(myPrint
}
// .
)(static void myPrint
{
;)"Console.WriteLine("Not a member of csharp-persian.tutorial.myExample.
}
}
// C# Persian Tutorial Namespace
namespace csharp-persian.tutorial
{
class myExample
{
)(public static void myPrint
{
;)"Console.WriteLine("This is a member of csharp-persian.tutorial.myExample.
}
}
}

www.Arsanjan.blogfa.com

47

Namespace
. ) (Alias . 6-6

csTut = csharp-persian.tutorial.myExample
csharp-persian.tutorial.myExample csTut .
. )( Main .
)( Main )( myPrint AliasDirective .
)( myPrint myExample .
alias )( myPrint myExample (csTut.myPrint()) .
. (csTut.myPrint()) alias
)( myPrint AliasDirective .
Namespace Namespace .
:
Classes
Structures
Interfaces
Enumerations
Delegates

Namespace Namespace .
Namespace using .
Namespace . (Alias
) Directive .

www.Arsanjan.blogfa.com

48

C#
C# . :
 )(Constructors
 ) (Instance )(Static
 )(Destructors

.
.
.
class }{
.
. .
. 7-1 .
// Namespace
;using System
class OutputClass
{
;string myString
//
)public OutputClass(string inputString
{
;myString = inputString
}
//
)(public void printString
{
;)Console.WriteLine("{0}", myString
}
//
)(~OutputClass
{
//
}
}
//
class ExampleClass
{

www.Arsanjan.blogfa.com

49

//
)(public static void Main
{
// OutputClass
;)"OutputClass outCl = new OutputClass("This is printed by the output class.
// Output
;)(outCl.printString
}
}

7-1 . OutPutClass .
myString .
)( . ) (inputString
. myString .
ExampleClass .
. .
.
) (Initializers . :
} { )"public OutputClass() : this("Default Constructor String

OutPutClass 7-1 .
":" . this . this
. .
this .
OutPutClass .
.
.
.
C# : .
. . )( Main
ExampleClass OutPutClass outCl .
OutPutClass . .
OutPutClass :
;)"OutputClass oc1 = new OutputClass("OutputClass1
;)"OutputClass oc2 = new OutputClass("OutputClass2

OutPutClass myString
)( printString .

www.Arsanjan.blogfa.com

50

> <class name>.<static class member .


oc1 oc2 . OutPutClass :
)(public static void staticPrinter
{
;)"Console.WriteLine("There is only one of me.
}

)( Main :
;)(OutputClass.staticPrinter
.
.
.
. .Net
Framework BCL Math .
.
. static .

. .
OutPutClass ) (Destructor .
"~" . .
.
Garbage Collector C#
Garbage Collector) . GC .Net Framework
C#
. GC .

(.

:
Constructors
Destructors
Fields
Methods
Properties
Indexers
Delegates
Events
Nested Classes
www.Arsanjan.blogfa.com

51

.
.
.

www.Arsanjan.blogfa.com

52


C# . :
 )(Base Class
 )(Derived Class



. .
.
)(Inheritance
;using System
public class ParentClass
{
)(public ParentClass
{
;)"Console.WriteLine("Parent Constructor.
}
)(public void print
{
;)"Console.WriteLine("I'm a Parent Class.
}
}
public class ChildClass : ParentClass
{
)(public ChildClass
{
;)"Console.WriteLine("Child Constructor.
}
)(public static void Main
{
;)(ChildClass child = new ChildClass
;)(child.print
}
}

:
Parent Constructor.
Child Constructor.
I'm a Parent Class.

www.Arsanjan.blogfa.com

53

8-1 . ParentClass ChildClass .


ParentClass .
ChildClass ParentClass
. public class ChildClass : ParentClass . " ":
.
C# . .
) (Interfaces .
ChildClass ParentClass . ChildClass ParentClass.
) ChildClass (ChildClass IS a ParentClass )( Print
ParentClass . .
. 8-1
. ParentClass ChildClass .


8-2 .
;using System
public class Parent
{
;string parentString
)(public Parent
{
;)"Console.WriteLine("Parent Constructor.
}
)public Parent(string myString
{
;parentString = myString
;)Console.WriteLine(parentString
}
)(public void print
{
;)"Console.WriteLine("I'm a Parent Class.
}
}
public class Child : Parent
{
)"public Child() : base("From Derived
{
;)"Console.WriteLine("Child Constructor.

www.Arsanjan.blogfa.com

54

}
)(public new void print
{
;)(base.print
;)"Console.WriteLine("I'm a Child Class.
}
)(public static void Main
{
;)(Child child = new Child
;)(child.print
;)(((Parent)child).print
}
}

:
From Derived
Child Constructor.
I'm a Parent Class.
I'm a Child Class.
I'm a Parent Class.
. 8-2
ChildClass . " " : base
. " "From Derived
.
. Child
)( Print . )( Print Child )( Print Parent
. )( Print )( Parent
.
)( Print Child )( Print Parent .
base . base public
protected . )( Print Child
.
Casting . )( Main
Child . .
Casting .
)( Print Parent .
new )( Print Child . )( Print Child
)( Print . new
www.Arsanjan.blogfa.com

55

.
) (Polymorphism .

.
. .

www.Arsanjan.blogfa.com

56

_ )(Polymorphism

C# . :


)(Virtual Method
Override

) (Polymorphism .
.
. .
.
. .

)(Virtual Method
;using System

public class DrawingObject


{
)(public virtual void Draw
{
;)"Console.WriteLine("I'm just a generic drawing object.
}
}

www.Arsanjan.blogfa.com

57

. . DrawingObject 9-1
virtual . virtual . Draw()
. override
using System;

public class Line : DrawingObject


{
public override void Draw()
{
Console.WriteLine("I'm a Line.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Circle.");
}
}
public class Square : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Square.");
}
}

www.Arsanjan.blogfa.com

58

9-2 . DrawingObject .
)( Draw override . override
override . override
.


;using System

public class DrawDemo


{
) (public static int Main
{
;]DrawingObject[] dObj = new DrawingObject[4
;)(dObj[0] = new Line
;)(dObj[1] = new Circle
;)(dObj[2] = new Square
;)(dObj[3] = new DrawingObject
)foreach (DrawingObject drawObj in dObj
{
;)(drawObj.Draw
}
;return 0
}
}

www.Arsanjan.blogfa.com

59

9-3 9-1 9-2 . .


)( Main . DrawingObject . dObj
DrawingObject .

dObj . DrawingObject Circle Line


Square .
.
.

foreach . foreach )( Draw


. DrawingObject dObj . )( Draw
override )( Draw . :
I'm a Line.
I'm a Circle.
I'm a Square.
I'm just a generic drawing object.
override )( Draw .
)( Draw DrawingObject DrawingObject.

.
.

www.Arsanjan.blogfa.com

60

C#
) (Properties C# . :
Property
Property
Property )(Read-Only
Property )(Write-Only
Property Property .
Property .
Property .
: 10-1
;using System
public class PropertyHolder
{
;private int someProperty = 0
)(public int getSomeProperty
{
;return someProperty
}
)public void setSomeProperty(int propValue
{
;someProperty = propValue
}
}
public class PropertyTester
{
)public static int Main(string[] args
{
;)(PropertyHolder propHold = new PropertyHolder
;)propHold.setSomeProperty(5
;))(Console.WriteLine("Property Value: {0}", propHold.getSomeProperty
;return 0
}
}

10-1 . PropertyHolder
. )( getSomeProperty )( setSomePropery.
)( getSomeProperty someProperty )( setSomeProperty
someProperty .

www.Arsanjan.blogfa.com

61

PropertyTester PropertyHolder someProperty


PropertyHolder . )( Main PropertyHolder propHold
. setSomeProperty someMethod propHold 5
property )( Console.WriteLine .
property )( getSomeProperty Property Value
: 5 .
.
someProperty int byte .
Property . .
: 10-2 Property
;using System
public class PropertyHolder
{
;private int someProperty = 0
public int SomeProperty
{
get
{
;return someProperty
}
set
{
;someProperty = value
}
}
}
public class PropertyTester
{
)public static int Main(string[] args
{
;)(PropertyHolder propHold = new PropertyHolder
;propHold.SomeProperty = 5
;)Console.WriteLine("Property Value: {0}", propHold.SomeProperty
;return 0
}
}

10-2 ) (Property . PropertyHolder


SomeProperty .
SomeProperty someProperty . accessor set getaccessor .
get someProperty set accessor . value
www.Arsanjan.blogfa.com

62

C# set accessor value . someProperty


.
. PropertyHolder someProperty PropertyTester
someProperty . propHold PropertyHolder Main()
5 SomeProperty propHold
.
. propHold someProperty Console.WriteLine()
. propHold SomeProperty
.( Read-Only)
. . get accessor
(Read-Only Properties)
: 10-3
using System;
public class PropertyHolder
{
private int someProperty = 0;
public PropertyHolder(int propVal)
{
someProperty = propVal;
}
public int SomeProperty
{
get
{
return someProperty;
}
}
}
public class PropertyTester
{
public static int Main(string[] args)
{
PropertyHolder propHold = new PropertyHolder(5);
Console.WriteLine("Property Value: {0}", propHold.SomeProperty);
return 0;
}
}

www.Arsanjan.blogfa.com

63

10-3 . PropertyHolder
SomeProperty get accessor . PropertyHolder
int .
)( Main PropertyTester PropertyHolder propHold .
PropertyHolder .
5 . 5 someProperty propHold
.
SomeProperty PropertyHolder
someProperty . propHold.SomeProperty = 7
SomeProperty .
)( Console.WriteLine
get accessor .
)(Write-Only Properties
:
: 10-4
;using System
public class PropertyHolder
{
;private int someProperty = 0
public int SomeProperty
{
set
{
;someProperty = value
;)Console.WriteLine("someProperty is equal to {0}", someProperty
}
}
}
public class PropertyTester
{
)public static int Main(string[] args
{
;)(PropertyHolder propHold = new PropertyHolder
;propHold.SomeProperty = 5
;return 0
}
}

www.Arsanjan.blogfa.com

64

10-4 . get accessor


SomeProperty set accessor .
)( Main PropertyTester .
SomeProperty propHold 5 someProperty propHold
. set accessor SomeProperty 5
someProperty someProperty is equal to 5 .

.
) (Property
. .
.

www.Arsanjan.blogfa.com

65

(Indexers) C#
C# . :

)(Overload


C# . .
.

. :

: 1-11
;using System
>/// <summary
///
>/// </summary
class IntIndexer
{
;private string[] myData
)public IntIndexer(int size
{
;]myData = new string[size
)for (int i=0; i < size; i++
{
;"myData[i] = "empty
}
}
]public string this[int pos
{
get
{
;]return myData[pos
}
set
{
;myData[pos] = value
}
}

www.Arsanjan.blogfa.com

66

)static void Main(string[] args


{
;int size = 10
;)IntIndexer myInd = new IntIndexer(size
;"myInd[9] = "Some Value
;"myInd[3] = "Another Value
;"myInd[5] = "Any Value
;)"Console.WriteLine("\nIndexer Output\n
)for (int i=0; i < size; i++
{
;)]Console.WriteLine("myInd[{0}]: {1}", i, myInd[i
}
}
}

1-11 . IntIndexer myData .


) (private ) (external users .
) (constructor size int
myData " "empty .
this .this[int pos]
pos .
) (property . accessor set get property .
.
)( Main IntIndexer .
:
Indexer Output
myInd[0]: empty
myInd[1]: empty
myInd[2]: empty
myInd[3]: Another Value
myInd[4]: empty
myInd[5]: Any Value
myInd[6]: empty
myInd[7]: empty
myInd[8]: empty
myInd[9]: Some Value

integer C#
. C# .
. enum integer : .string
) (Overload . 11-2
.
www.Arsanjan.blogfa.com

67


(Overloaded Indexers) : 11-2
using System;
/// <summary>
///
/// </summary>
class OvrIndexer
{
private string[] myData;
private int arrSize;
public OvrIndexer(int size)
{
arrSize = size;
myData = new string[size];
for (int i=0; i < size; i++)
{
myData[i] = "empty";
}//end of for
}//end of constructor
public string this[int pos]
{
get
{
return myData[pos];
}
set
{
myData[pos] = value;
}
}//end of indexer
public string this[string data]
{
get
{
int count = 0;
for (int i=0; i < arrSize; i++)
{
if (myData[i] == data)
{
count++;
}//end of if
}//end of for

www.Arsanjan.blogfa.com

68

;)(return count.ToString
}//end of get
set
{
)for (int i=0; i < arrSize; i++
{
)if (myData[i] == data
{
;myData[i] = value
}//end of if
}//end of for
}//end of set
}//end of overloaded indexer
)static void Main(string[] args
{
;int size = 10
;)OvrIndexer myInd = new OvrIndexer(size
;"myInd[9] = "Some Value
;"myInd[3] = "Another Value
;"myInd[5] = "Any Value
;"myInd["empty"] = "no value
;)"Console.WriteLine("\nIndexer Output\n
)for (int i=0; i < size; i++
{
;)]Console.WriteLine("myInd[{0}]: {1}", i, myInd[i
}//end of for
;)]"Console.WriteLine("\nNumber of \"no value\" entries: {0}", myInd["no value
)(}//end of Main
}//end of class

11-2 . int pos


11-1 string get accessor .
data set .
accessor data
.
) (behavior string )( Main .
set accessor " "No value myInd " "empty
. accessor . myInd["empty"] = "No value" :
myInd " "No value .
get accessor .myInd["No value"] : :
Indexer Output

www.Arsanjan.blogfa.com

69

myInd[0]: no value
myInd[1]: no value
myInd[2]: no value
myInd[3]: Another Value
myInd[4]: no value
myInd[5]: Any Value
myInd[6]: no value
myInd[7]: no value
myInd[8]: no value
myInd[9]: Some Value
Number of "no value" entries: 7

11-2 .
.

. :
]public object this[int param1, ..., int paramN
{
get
{
// process and return some class data
}
set
{
// process and assign some class data
}
}

:
.
. .
.

:
.1
) (Overloading .

.

.2

. .
www.Arsanjan.blogfa.com

70

.3
ListBox ListBox) .
.

. ListBox Word

ListBox (.
string .
update .
. property
this this .
public class ListBox: Control
{
;private string[] items
]public string this[int index
{
get
{
;]return items[index
}
set
{
;items[index] = value
;)(Repaint
}
}
}

. ListBox :
;ListBox listBox = ...
;"listBox[0] = "hello
;)]Console.WriteLine(listBox[0

ListBox :
Csharp-Persian_Indexer_Demo
;using System
public class ListBoxTest
{
ListBox //.
)public ListBoxTest(params string[] initialStrings

www.Arsanjan.blogfa.com

71

{
// .
strings = new String[256];
// .
foreach (string s in initialStrings)
{
strings[ctr++] = s;
}
}//end of constructor
// .
public void Add(string theString)
{
if (ctr >= strings.Length)
{
// .
}
else
strings[ctr++] = theString;
}//end of Add()
//
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
// .
}
return strings[index];
}//end of get
set
{
if (index >= ctr )
{
//
}
else
strings[index] = value;
}//end of set
}//end of indexer
//
public int GetNumEntries( )

www.Arsanjan.blogfa.com

72

{
;return ctr
}
;private string[] strings
;private int ctr = 0
}//end of ListBoxTest class
public class Tester
{
) (static void Main
{
ListBox //
;)"ListBoxTest lbt = new ListBoxTest("Hello", "World
// .
;)"lbt.Add("Who
;)"lbt.Add("Is
;)"lbt.Add("John
;)"lbt.Add("Galt
// .
;"string subst = "Universe
;lbt[1] = subst

// .
)for (int i = 0;i<lbt.GetNumEntries( );i++
{
;)]Console.WriteLine("lbt[{0}]: {1}",i,lbt[i
}
)(}//end of Main
}//end of Tester class

:
Output:
Hello
Universe
Who
Is
John
Galt

lbt[0]:
lbt[1]:
lbt[2]:
lbt[3]:
lbt[4]:
lbt[5]:

:
.
.
.

www.Arsanjan.blogfa.com

73

C#
.
.

www.Arsanjan.blogfa.com

74

(Struct) C#
) (Struct C# .
struct ) (Structure
)(Struct
)(Struct
struct

) (struct
) (types struct
) (value types . struct
struct struct .
property .
. Point Framework SDK
property X Y.
) (struct (int,
) float, . ) (struct
C# . .
) (struct .
) (struct .

struct
struct struct .
}{ . :
: 12-1 )(Struct
;using System
struct Point
{
;public int x
;public int y
)public Point(int x, int y
{
;this.x = x
;this.y = y
}
)public Point Add(Point pt
{
;Point newPt

www.Arsanjan.blogfa.com

75

;newPt.x = x + pt.x
;newPt.y = y + pt.y
;return newPt
}
}
>/// <summary
/// struct
>/// </summary
class StructExample
{
)static void Main(string[] args
{
;)Point pt1 = new Point(1, 1
;)Point pt2 = new Point(2, 2
;Point pt3
;)pt3 = pt1.Add(pt2
;)Console.WriteLine("pt3: {0}:{1}", pt3.x, pt3.y
}
}

12-1 struct . ) (type struct


struct . struct
. Point
x y . )( Add
Point struct struct .
Point )( Add .
new .
) ( .
. Boolean false .
) . struct
(.
) (structs new ) (.
pt1 12-1 pt2 Point Point
. pt3 Point .
)( Add pt1 pt2 . pt3
. 12-1
:
pt3 : 3 : 3
) (deconstructor.
. interface . interface
www.Arsanjan.blogfa.com

76

C# . interface
. interface .

:
.
.
.
) (Stack heap .


.1
) struct (syntax
.
struct
struct . :
struct Time
{
public Time() { ... } //

struct .
struct calss .
struct .

struct !
struct
false null struct

. Time
struct :
struct Time
{
)public Time(int hh, int mm
{
;hours = hh
;minutes = mm
}
: seconds not initialized //

www.Arsanjan.blogfa.com

77

;private int hours, minutes, seconds


}

struct
struct . struct
:
struct Time
{

private int hours = 0; //


;private int minutes
;private int seconds
}

struct .
struct struct )(interface
.

.2
) (Value Types .
.
.
struct Time
{

;private int hours, minutes, seconds


}
class Example
{
)public void Method(Time parameter
{
;Time localVariable

}
;private Time field
}


stack . .

www.Arsanjan.blogfa.com

78

)(Interfaces
C# . :
-1
-2
-3 interface
-4 interface
-5
-6
-7
.
interface property .
interface property
property .
interface
interface
. interface
property interface .
property .
interface
) (transact . .
int . int
long .
. . side effect
).
side effect (. interface .
int long user
interface .
.
interface .
interface ) ( ) (GUI .
interface
.
www.Arsanjan.blogfa.com

79

) (Abstract . )
abstract (. :
. interface
static final . interface .
" :
".
.

) (protocol .
) interface protocol (.

interface
. A IDisposable
A )( Dispose interface . A
A IDisposable .
)( A.Dispose . .
interface IMyInterface
{
;)(void MethodToImplement
}

IMyInterface . ) !(
" "I interface . interface .
.
. }{
; . interface
. .
: 13-1
class InterfaceImplementer : IMyInterface
{
)(static void Main
{
;)(InterfaceImplementer iImp = new InterfaceImplementer
;)(iImp.MethodToImplement
}
)(public void MethodToImplement
{
;)"Console.WriteLine("MethodToImplement() called.

www.Arsanjan.blogfa.com

80

}
}

InterfaceImplementer IMyInterface .
.
)( MethodToImplement .

. .
: 13-2
;using System
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.
}
}

13-2 2 : IMyInterface .IParentInterface



. 13-2 InterfaceImplementer
IMyInterface IParentInterface
.
www.Arsanjan.blogfa.com

81

:
-1 interface ) (Reference Type .
-2
"" "" ) (is-a relation ) (
interface "" ) (implement relation ") .
" (.
-3 interface :
[:base-

interface-name

interface

][attributes] [access-modifier
}list]{interface-body

:
attributes :
public access-modifiers : private
interface-name :
:base-list : .
Interface-body :
virtual .
-4 interface .
-5 :
property
/ .
IStorable .
)( Read )( Write
interface IStorable
{
;) (void Read
;)void Write(object
}

Document /
IStorable .
public class Document : IStorable
{
}public void Read( ) {...
}public void Write(object obj) {...
// ...
}


. 13-3 .

www.Arsanjan.blogfa.com

82

: 13-3
using System;
// interface
interface IStorable
{
void Read( );
void Write(object obj);
int Status { get; set; }
}
public class Document : IStorable
{
public Document(string s)
{
Console.WriteLine("Creating document with: {0}", s);
}
public void Read( )
{
Console.WriteLine("Implementing the Read Method for IStorable");
}
public void Write(object o)
{
Console.WriteLine("Implementing the Write Method for IStorable");
}
public int Status
{
get
{
return status;
}
set
{
status = value;
}
}
private int status = 0;
}
public class Tester
{
static void Main( )
{
Document doc = new Document("Test Document");
doc.Status = -1;
doc.Read( );
Console.WriteLine("Document Status: {0}", doc.Status);

www.Arsanjan.blogfa.com

83

;IStorable isDoc = (IStorable) doc


;isDoc.Status = 0
;) (isDoc.Read
;)Console.WriteLine("IStorable Status: {0}", isDoc.Status
}
}

:
Output:
Creating document with: Test Document
Implementing the Read Method for IStorable
Document Status: -1
Implementing the Read Method for IStorable
IStorable Status: 0

-6 IStorable ) public,private (...


.
.
-7 .
-8
.
.

:
.
. .

.

www.Arsanjan.blogfa.com

84

delegate C#

delegate
.

. C#
delegate delegate
.
:

delegate
delegate
delegate
delegate
delegate
delegate ) (
delegate ) (
) delegate (
event






delegate

) (Reference Type C#
) (Class ) (Interface .
.
) (Attribute ) (Behavior .

. ) (Reference Type C# .
www.Arsanjan.blogfa.com

85

delegate
.

.
) (GUI

. . ...
" " ) (Event-Based Programming
.
. .
.
) (Events . C#
Event Delegate .
event handler
Event handler . C# delegate .
delegate Callback " :
" . delegate
.

Delegate
Delegate C#
delegate . C
. C ) (pointer .

. .
delegate . delegate
) (Abstraction .
.
.
.

www.Arsanjan.blogfa.com

86

delegate delegate
.
.

. ) (reusable
.
) (sort
.
if/then/else switch
.
delegate
delegate . .
delegate
. 14-1 .
) : .
. ) (type
.
. int string .
delegate .
delegate (.
: 14-1 delegate
;using System
delegate // .
;)public delegate int Comparer(object obj1, object obj2
public class Name
{
;public string FirstName = null
;public string LastName = null
)public Name(string first, string last
{
;FirstName = first
;LastName = last
}
// delegate method handler
)public static int CompareFirstNames(object name1, object name2
{
;string n1 = ((Name)name1).FirstName
;string n2 = ((Name)name2).FirstName
)if (String.Compare(n1, n2) > 0

www.Arsanjan.blogfa.com

87

{
return
}
else if
{
return
}
else
{
return
}

1;
(String.Compare(n1, n2) < 0)
-1;

0;

}
public override string ToString()
{
return FirstName + " " + LastName;
}
}
class SimpleDelegate
{
Name[] names = new Name[5];
public SimpleDelegate()
{
names[0] = new Name("Meysam", "Ghazvini");
names[1] = new Name("C#", "Persian");
names[2] = new Name("Csharp", "Persian");
names[3] = new Name("Xname", "Xfamily");
names[4] = new Name("Yname", "Yfamily");
}
static void Main(string[] args)
{
SimpleDelegate sd = new SimpleDelegate();
// delegate
Comparer cmp = new Comparer(Name.CompareFirstNames);
Console.WriteLine("\nBefore Sort: \n");
sd.PrintNames();
sd.Sort(cmp);
Console.WriteLine("\nAfter Sort: \n");
sd.PrintNames();
}
public void Sort(Comparer compare)
{
object temp;
for (int i=0; i < names.Length; i++)
{
for (int j=i; j < names.Length; j++)
{
// compare
if ( compare(names[i], names[j]) > 0 )

www.Arsanjan.blogfa.com

88

{
;]temp = names[i
;]names[i] = names[j
;names[j] = (Name)temp
}
}
}
}
)(public void PrintNames
{
;)"Console.WriteLine("Names: \n
)foreach (Name name in names
{
;))(Console.WriteLine(name.ToString
}
}
}

delegate . delegate
delegate ";" . delegate
14-1 :
;)public delegate int Comparer(object obj1, object obj2

delegate . delegate
handler Comparer object
int . delegate handler 14-1
:
)public static int ComparerFirstNames(object name1, object name2
{

delegate . delegate
delegate handler :
;)Comparer cmp = new Comparer(Name.ComparerFirstName

cmp 14-1 )( Sort . delegate


)( Sort :
;)sd.Sort(cmp

delegate handler )( Sort .


handler )( CompareLastNames Comparer
)( Sort .

www.Arsanjan.blogfa.com

89

delegate
delegate . delegate
. .
delegate .


. C#
delegate delegate .
delegate
.

. :
class Ticker
{

)public void Attach(Subscriber newSubscriber


{
;)subscribers.Add(newSubscriber
}
)public void Detach(Subscriber exSubscriber
{
;)subscribers.Remove(exSubscriber
}
Notify //
)(private void Notify
{
)foreach (Subscriber s in subscribers
{
;)(s.Tick
}
}

;)(private ArrayList subscribers = new ArrayList


}
class Subscriber
{
)(public void Tick
{

}
}
class ExampleUse
{
)(static void Main

www.Arsanjan.blogfa.com

90

{
Ticker pulsed = new Ticker();
Subscriber worker = new Subscriber();
pulsed.Attach(worker);

}
}

Subscriber Ticker .
. Ticker Subscriber .
Ticker
Tick .( Interface) .
. Ticker
interface Tickable
{
void Tick();
}
class Ticker
{
public void Attach(Tickable newSubscriber)
{
subscribers.Add(newSubscriber);
}
public void Detach(Tickable exSubscriber)
{
subscribers.Remove(exSubscriber);
}
// Notify
private void Notify()
{
foreach (Tickable t in subscribers)
{
t.Tick();
}
}

private ArrayList subscribers = new ArrayList();


}

. Tickable
class Clock : Tickable
{

public void Tick()


{

www.Arsanjan.blogfa.com

91

}
class ExampleUse
{
)(static void Main
{
;)(Ticker pulsed = new Ticker
;)(Clock wall = new Clock
;)pulsed.Attach(wall

}
}

delegate .

delegate
.
. )
.GUI (.
Tick public Clock.Tick
. Clock.Tick
. delegate
.

Delegate
Tick Tickable void :
interface Tickable
{
;)(void Tick
}

delegate :
;)(delegate void Tick

.
:
)void Example(Tick param
{

delegate
www.Arsanjan.blogfa.com

92

delegate . param
param int +
. param int param delegate delegate
delegate . delegate :
)void Example(Tick param
{
;)(param
}

: delegate Null .
param Null NullReferenceException .
delegate . Tick
delegate param
delegate void .
)void Example(Tick param
{
//
;)param(42
;)(int hhg = param
//
Console.WriteLine(param()); //
}

delegate . Tick :
;)delegate void Tick(int hours, int minutes, int seconds

:
)void Example(Tick method
{
;)method(12, 29, 59
}

delegate Ticker :
;)delegate void Tick(int hours, int minutes, int seconds
class Ticker
{

)public void Attach(Tick newSubscriber


{
;)subscribers.Add(newSubscriber
}
)public void Detach(Tick exSubscriber
{
;)subscribers.Remove(exSubscriber
}
)private void Notify(int hours, int minutes, int seconds

www.Arsanjan.blogfa.com

93

{
)foreach (Tick method in subscribers
{
;)method(hours, minutes, seconds
}
}

;)(private ArrayList subscribers = new ArrayList


}

delegate
delegate . delegate
.
class Clock
{

)public void RefreshTime(int hours, int minutes, int seconds


{

Tick RefreshTime delegate :


;)delegate void Tick(int hours, int minutes, int seconds

Tick RefreshTime
Clock.
;)(Clock wall = new Clock

;)Tick m = new Tick(wall.RefreshTime

m :
;)m(12, 29, 59

) m ( :
;)wall.RefreshTime(12, 29, 59

m . delegate
. Ticker Clock
. RefreshTime private :
;)delegate void Tick(int hours, int minutes, int seconds

class Clock
{

)(public void Start


{
;))ticking.Attach(new Tick(this.RefreshTime
}

www.Arsanjan.blogfa.com

94

)(public void Stop


{
;))ticking.Detach(new Tick(this.RefreshTime
}
)private void RefreshTime(int hours, int minutes, int seconds
{
;)Console.WriteLine("{0}:{1}:{2}", hours, minutes, seconds
}
;)(private Ticker ticking = new Ticker
}

delegate .

)(Events
Console
. . Console
GUI ) (Event-Based
) (.
.
.
event C# .
event fires raised .
.
delegate

.
Delegate .
.
. delegate delegate
Delegate . delegate
.Net delegate . delegate
. .
: 14-2
;using System
;)(public delegate void MyDelegate

www.Arsanjan.blogfa.com

95

class Listing14-2
{
public static event MyDelegate MyEvent;
static void Main()
{
MyEvent += new MyDelegate(CallbackMethod);
//
MyEvent();
Console.ReadLine();
}
public static void CallbackMethod()
{
Console.WriteLine("CallbackMethod.");
}
}

MyDelegate MyEvent . delegate


. MyEvent Main() .
MyEvent . += delegate
) . delegate CallbackMethod
(.
delegate 14-2 .
:
using System;
public delegate void MyDelegate();
class UsingDelegates
{
static void Main()
{
MyDelegate del = new MyDelegate(CallbackMethod);
// delegate
del();
Console.ReadLine();
}
public static void CallbackMethod()
{
Console.WriteLine("CallbackMethod.");

www.Arsanjan.blogfa.com

96

}
}


. event
delegate .
delegate . .
. delegate
.

:
. delegate
delegate Tick . delegate :
;)delegate void Tick(int hours, int minutes, int seconds

. tick Tick :
class Ticker
{
;public event Tick tick

: .
) (
delegate = + . Clock
Ticker pulsed . Ticker tick delegate Tick
. delegate Clock.Start Tick = + pulsed.tick.
;)delegate void Tick(int hours, int minutes, int seconds
class Ticker
{
;public event Tick tick

}
class Clock

www.Arsanjan.blogfa.com

97

)(public void Start


{
;)pulsed.tick += new Tick(this.RefreshTime
}

)private void RefreshTime(int hours, int minutes, int seconds


{

}
;)(private Ticker pulsed = new Ticker
}

pulsed.tick delegate
RefreshTime) . delegate (.


= + delegate = - delegate
.
class Clock
{

)(public void Stop


{
;)pulsed.tick -= new Tick(this.RefreshTime
}
)private void RefreshTime(int hours, int minutes, int seconds
{

}
;)(private Ticker pulsed = new Ticker
}

: = + = - + . delegate
+ . + delegate delegate
delegate .

delegate . delegate
. Ticker private
Notify tick :
class Ticker
{

www.Arsanjan.blogfa.com

98

;public event Tick tick

)private void Notify(int hours, int minutes, int seconds


{
)if (tick != null
{
;)tick(hours, minutes, seconds
}
}

: null tick null

null delegate .
null NullReferenceException .
. public
. tick Ticker
Ticker tick .
class Example
{
)(static void Main
{
;)(Ticker pulsed = new Ticker
pulsed.tick(12, 29, 59); //
}
}



GUI . Console
GUI .
GUI ...
.

.
GUI .Net Framework .
) (Button .
Button Button) . System.Windows.Forms( . Button Control
Click EventHandler . .
namespace System

www.Arsanjan.blogfa.com

99

{
public delegate void EventHandler(object sender, EventArgs args);
public class EventArgs
{

}
}
namespace System.Windows.Forms
{
public class Control :
{
public event EventHandler Click;

}
public class Button : Control
{

}
}

. System namespace
namespace . EventHandler delegate System
Button Click System.Windows.Forms
. Control
. Click Button
. delegate
. Okay_Click Okay Okay_Click Okay
class Example : System.Windows.Forms.Form
{
private System.Windows.Forms.Button okay;

public Example()
{
this.okay = new System.Windows.Forms.Button();
this.okay.Click += new System.EventHandler(this.okay_Click);

}
private void okay_Click(object sender, System.EventsArgs args)
{

}
}

www.Arsanjan.blogfa.com

100

Example System.Windows.Forms.Form
Okay . Button . ) (Constructor Example
Okay.Click this.Okay.Click .
EventHandler delegate . Okay_Click
. Okay Okay_Click
.
Visual Studio.Net C#Builder
Okay_Click .
GUI .
delegate ) (void .
EventArgs EventArgs.
sender delegate ) .
(.

delegate event

Delegate System.Delegate Delegate . property


.
System.Delegate .Net Framework delegate C#
Visual Basic.Net .
delegate
.
delegate .
.

. .
.

www.Arsanjan.blogfa.com

101

- )(Exception Handling
) ( C# .
:
(1 Exception
(2 try/catch
(3 finally
.
.
Null .

.
.
I/O .

. ) (Exception Handling .
thrown . thrown
System.Exception .
try/catch .
System.Exception property
. Message property
StackTrace . ) Stack( Stack
.

. )(System.IO.File.OpenRead
) (Thrown :
SecurityException
ArgumentException
ArgumentNullException
PathTooLongException
DirectoryNotFoundException
UnauthorizedAccessException
FileNotFoundException

www.Arsanjan.blogfa.com

102

NotSupportedException

.Net Framework SDK


. Reference/Class Library Namespace/Class/Method
.
.
.
thrown ) ( .
try/catch .
try catch .
15-1 try/catch . )( OpenRead
try . catch
. 15-1
Stack .
:
.
;using System
;using System.IO
class TryCatchDemo
{
)static void Main(string[] args
{
try
{
;)"File.OpenRead("NonExistentFile
}
)catch(Exception ex
{
;))(Console.WriteLine(ex.ToString
}
}
}

15-1 catch
Exception .
. catch
:
)catch(FileNotFoundException fnfex

www.Arsanjan.blogfa.com

103

{
;))(Console.WriteLine(fnfex.ToString
}
)catch(Exception ex
{
;))(Console.WriteLine(ex.ToString
}

FileNotFoundException catch
. PathTooLongException catch
. PathTooLongException catch
Exception . catch
.
Stack try/catch
. try/catch
. .
.

. catch
.
finally .
15-2 finally .

. .
outStream 15-2 handle .
inStraem FileNotFound
catch .
catch outStream . catch .
outStream
. . finally
.
. finally .
.
;using System

www.Arsanjan.blogfa.com

104

;using System.IO
class FinallyDemo
{
)static void Main(string[] args
{
;FileStream outStream = null
;FileStream inStream = null
try
{
;)"outStream = File.OpenWrite("DestinationFile.txt
;)"inStream = File.OpenRead("BogusInputFile.txt
}
)catch(Exception ex
{
;))(Console.WriteLine(ex.ToString
}
finally
{
)if (outStream != null
{
;)(outStream.Close
;)"Console.WriteLine("outStream closed.
}
)if (inStream != null
{
;)(inStream.Close
;)"Console.WriteLine("inStream closed.
}
}
}
}

finally .
: catch finally
. finally
catch
. .
catch
catch .
finally .
. .
try/catch .
finally
.
www.Arsanjan.blogfa.com

105

C#
C# . :
-1
-2
-3 ) Named (Positional
Target -4 ) (
-5
-6
-7 Positional Named
-8 ) (type
-9
-10
-11
.
... .
. DllImportAttribute
Win32 .
. ObsoleteAttribute

.
property .
.Net .
.

. .
Metadata . C#
Dll . Metadata
. Reflection Metadata
). . Metadata " "
(. C#
. Reflection
.

www.Arsanjan.blogfa.com

106


.
.
[ObsoleteAttribute]
: Attribute
[Obsolete]
.
. ObsoleteAttribute 16-1
: 16-1
using System;
class BasicAttributeDemo
{
[Obsolete]
public void MyFirstDeprecatedMethod()
{
Console.WriteLine("Called MyFirstDeprecatedMethod().");
}
[ObsoleteAttribute]
public void MySecondDeprecatedMethod()
{
Console.WriteLine("Called MySecondDeprecatedMethod().");
}
[Obsolete("You shouldn't use this method anymore.")]
public void MyThirdDeprecatedMethod()
{
Console.WriteLine("Called MyThirdDeprecatedMethod().");
}
// make the program thread safe for COM
[STAThread]
static void Main(string[] args)
{
BasicAttributeDemo attrDemo = new BasicAttributeDemo();
attrDemo.MyFirstDeprecatedMethod();
attrDemo.MySecondDeprecatedMethod();
attrDemo.MyThirdDeprecatedMethod();
}
}

www.Arsanjan.blogfa.com

107

16-1 Obsolete .
)( MyFirstDeprecatedMethod
)( MySecondDeprecatedMethod .
Attribute . .
:
])"[Obsolete("You shouldn't use this method anymore.
)(public void MyThirdDeprecatedMethod
...

.
. C# .
>csc BasicAttributeDemo.cs
Microsoft (R) Visual C# .NET Compiler version 7.10.2292.4
for Microsoft (R) .NET Framework version 1.1.4322
Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.
BasicAttributeDemo.cs(29,3): warning CS0612:
'BasicAttributeDemo.MyFirstDeprecatedMethod()' is obsolete
BasicAttributeDemo.cs(30,3): warning CS0612:
'BasicAttributeDemo.MySecondDeprecatedMethod()' is obsolete
BasicAttributeDemo.cs(31,3): warning CS0618:
'BasicAttributeDemo.MyThirdDeprecatedMethod()' is obsolete: 'You
'shouldn't use this method anymore.


.
.
16-1 . STAThreadAttribute
C# )( Main . C#
COM Simple Threading Apartment .

COM ) .
(.
. 16-2 .
16-2
;using System
public class AnyClass
{
])[Obsolete("Don't use Old method, use New method", true

www.Arsanjan.blogfa.com

108

} { ) (static void Old


} { ) (static void New
) (public static void Main
{
;) (Old
}
}

16-2 .
16-1 . .
True
. False
. .
'use New method

AnyClass.Old()' is obsolete: 'Don't use Old method,

) Positional (Named
. .
) (positional ) .(named positional
! Obsolete
positional error int 16-1 .
16-2 positional
.
])[Obsolete("Don't use Old method, use New method", true
} { ) (static void Old

positional named named


. 16-3 DllImport
positional named.
16-3

;using System
;using System.Runtime.InteropServices
class AttributeParamsDemo
{

www.Arsanjan.blogfa.com

109

])"[DllImport("User32.dll", EntryPoint="MessageBox
static extern int MessageDialog(int hWnd, string msg, string
;)caption, int msgType
][STAThread
)static void Main(string[] args
{
MessageDialog(0, "MessageDialog Called!", "DllImport Demo",
;)0
}
}

DllImport 16-3 ("User32.dll") positional named


)" (EntryPoint="MessageBox . named
positional . named
positional
.
DllImport
Win32 API.
Positional ) (Constructor
Named
.

Target ) (
. C#
. 16-1 C#
.

....
.


all

assembly

class

constructor

Delegate

delegates

enum

event

field

interface
www.Arsanjan.blogfa.com

110

method

)
(.

module

parameter

Property

property

returnvalue

struc

Target Target
. CLS
CLSCompliantAttribute CLS . Common Language Specification
.Net Target . Target
. 16-4 .
16-4
;using System
])[assembly:CLSCompliant(true
public class AttributeTargetDemo
{
)public void NonClsCompliantMethod(uint nclsParam
{
;)"Console.WriteLine("Called NonClsCompliantMethod().
}
][STAThread
)static void Main(string[] args
{
;uint myUint = 0
;)(AttributeTargetDemo tgtDemo = new AttributeTargetDemo
;)tgtDemo.NonClsCompliantMethod(myUint
}
}

Target assembly .
16-4 uint )( NonClsCompliantMethod .
CLSCompliant false )( NonClsCompliantMethod
CLS ) int ( ) . CLS
CLS .Net Framework
www.Arsanjan.blogfa.com

111

.Net
.
uint
CLS CLS (.
16-4 CLSCompliant Target
assembly
.

.Net CLS
.


.
) (Attribute System.Attribute .
System.Attribute ) ( )(Attribute Class
. . 16-5
.
16-5
;using System
public class HelpAttribute : Attribute
{
}

.
])([Help
public class AnyClass
{
}

Attribute .
.
16-6
;using System
public class HelpAttribute : Attribute
{
)public HelpAttribute(String Descrition_in
{

www.Arsanjan.blogfa.com

112

;this.description = Description_in
}
;protected String description
public String Description
{
get
{
;return this.description
}
}
}
])"[Help("this is a do-nothing class
public class AnyClass
{
}

. property
.


AttributeUsage
.
property
.

ValidOn
property
. AttributeTarget OR
.

AllowMultiple
property
.

Inherited
property . property

.

www.Arsanjan.blogfa.com

113

-7 .
. 16
16-7
using System;
[AttributeUsage(AttributeTargets.Class), AllowMultiple =
false, Inherited = false ]
public class HelpAttribute : Attribute
{
public HelpAttribute(String Description_in)
{
this.description = Description_in;
}
protected String description;
public String Description
{
get
{
return this.description;
}
}
}

Help . AttributeTargets.Class
.
:
[Help("this is a do-nothing class")]
public class AnyClass
{
[Help("this is a do-nothing method")]
public void AnyMethod()
{
}
}

//error

:
AnyClass.cs: Attribute 'Help' is not valid on this declaration type.
It is valid on 'class' declarations only.

Help AttributeTargets.All
: .

Assembly,
Module,
Class,
Struct,
Enum,

www.Arsanjan.blogfa.com

114

Constructor,
Method,
Property,
Field,
Event,
Interface,
Parameter,
Delegate,
All = Assembly , Module , Class , Struct , Enum ,
Constructor , Method , Property , Field , Event , Interface
, Parameter , Delegate,
ClassMembers = Class , Struct , Enum , Constructor ,
Method , Property , Field , Event , Delegate , Interface

Help . AllowMultiple = false


: .
[Help("this is a do-nothing class")]
[Help("it contains a do-nothing method")]
public class AnyClass
{
[Help("this is a do-nothing method")]
public void AnyMethod()
{
}
}

//error

:
AnyClass.cs: Duplicate 'Help' attribute

. Inherited
.
. True
:
[Help("BaseClass")]
public class Base
{
}
public class Derive :
{
}

Base

:
www.Arsanjan.blogfa.com

115

[AttributeUsage(AttributeTargets.Class,
Inherited = false ]
[AttributeUsage(AttributeTargets.Class,
Inherited = false ]
[AttributeUsage(AttributeTargets.Class,
Inherited = true ]
[AttributeUsage(AttributeTargets.Class,
Inherited = true ]

AllowMultiple
AllowMultiple
AllowMultiple
AllowMultiple

=
=
=
=

false,
true,
false,
true,

Named Positional
Positional
. Help .
16-8
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false,
Inherited = false)]
public class HelpAttribute : Attribute
{
public HelpAttribute(String Description_in)
{
this.description = Description_in;
this.verion = "No Version is defined for this class";
}
protected String description;
public String Description
{
get
{
return this.description;
}
}
protected String version;
public String Version
{
get
{
return this.version;
}
//if we ever want our attribute user to set this property,
//we must specify set method for it
set
{
this.verion = value;
}
}
}

www.Arsanjan.blogfa.com

116

])"[Help("This is Class1
public class Class1
{
}
])"[Help("This is Class2", Version = "1.0
public class Class2
{
}
[Help("This is Class3", Version = "2.0", Description = "This is do])"nothing class
public class Class3
{
}

Class1 :
Help.Description : This is Class1
Help.Version :No Version is defined for this class

Version .
.
Help.Description : This is Class2
Help.Version : 1.0

Named .
Named property set
:
'Version' : Named attribute argument can't be a read only property

.
Help Description set .
Help.Description : This is do-nothing class
Help.Version : 2.0

) (Constructor Positional
set Named .

) (type

www.Arsanjan.blogfa.com

117

:
bool,byte,char,double,float,int,long,short,string,System.Type ,object

. enum


.
( query) .
( Types) Reflection . Reflection
Metadate .Net Framework Reflection .
16-9 .
.
Reflection : 16-9
using System;
using System.Reflection;
using System.Diagnostics;
//attaching Help attribute to entire assembly
[assembly : Help("This Assembly demonstrates
creation and their run-time query.")]
//our custom attribute class
public class HelpAttribute : Attribute
{
public HelpAttribute(String Description_in)
{
//
// TODO: Add constructor logic here
this.description = Description_in;
//
}
protected String description;
public String Description
{
get
{
return this.deescription;
}
}
}
//attaching Help attribute to our AnyClass
[HelpString("This is a do-nothing Class.")]
public class AnyClass

www.Arsanjan.blogfa.com

custom

attributes

118

{
//attaching Help attribute to our AnyMethod
])"[Help("This is a do-nothing Method.
)(public void AnyMethod
{
}
//attaching Help attribute to our AnyInt Field
])"[Help("This is any Integer.
;public int AnyInt
}
class QueryApp
{
)(public static void Main
{
}
}

.

. Reflection .

:
. .Net Framework
.
. Reflection
. .

www.Arsanjan.blogfa.com

119

: C#
) (Enumerator Types C# .
:
enum


System.Enum
enmu ) (Value Type System.Enum
. enum
.
enum
) (Sequential . enum
Enum .
.
enum enum
.
enum ) (Value Type .
enum .
C# enum Enum . C# enum BCL
Enum ! enum Enum
.


.Net Framework BCL enum .
MessageBox MessageBoxIcon .
.Net Framework
. enum
.
enum :
><modifier> enum <enum_name
{
www.Arsanjan.blogfa.com

120

// Enumeration list
}
. enum 17-1

enum : 17-1
using System;
// declares the enum
public enum Volume
{
Low,
Medium,
High
}
// demonstrates how to use the enum
class EnumSwitch
{
static void Main()
{
// create and initialize
// instance of enum type
Volume myVolume = Volume.Medium;
// make decision based
// on enum value
switch (myVolume)
{
case Volume.Low:
Console.WriteLine("The volume has been turned Down.");
break;
case Volume.Medium:
Console.WriteLine("The volume is in the middle.");
break;
case Volume.High:
Console.WriteLine("The volume has been turned up.");
break;
}
Console.ReadLine();
}
}

www.Arsanjan.blogfa.com

121

17-1 enum .
enum . } {
.
Volume )( Main myVolume
. enum . myVolume
int . switch myVolume
enum .
enum enum Volume
) (Volume.Medium enum
enum .
enum
. enum
. 17-1 Low 1 2 .
C# enum .
.
enum Months
{
jan, feb, mar, apr
}
enum Months
{
jan = 10, feb = 20, mar = 30, apr=40
}

mar = feb = 1 jan = 0


2 apr = 3 . enum
.
enum
. :
//;int x = Months.jan
// ; int x = (int) Months.jan

enum Casting .
. (int) Months.jan
www.Arsanjan.blogfa.com

122

int jan
. int enum
. enum
.

enum : 17-2
using System;
// declares the enum
public enum Volume : byte
{
Low = 1,
Medium,
High
}
class EnumBaseAndMembers
{
static void Main()
{
// create and initialize
// instance of enum type
Volume myVolume = Volume.Low;
// make decision based
// on enum value
switch (myVolume)
{
case Volume.Low:
Console.WriteLine("The volume has been turned Down.");
break;
case Volume.Medium:
Console.WriteLine("The volume is in the middle.");
break;
case Volume.High:
Console.WriteLine("The volume has been turned up.");
break;
}
Console.ReadLine();
}
}

enum . enum 17-2


. enum byte . byte

www.Arsanjan.blogfa.com

123

enum Low .
Low Middle=2 High=3 .

enum
C# enum 4 .
sizeof . enum .
enum C# enum
enum Metadata
. enum .
:
enum Language
{
CSharp,MCpp,VBNet,JScript,IL
}
class App
{
)(public static void Main
{
Console.WriteLine("Write
the
number
of
the
selected
;)"Language
;))"string[] langAr = Enum.GetNames(Type.GetType("Language
)for(int i=0;i<langAr.Length;i++
{
;)]Console.WriteLine(i + "." + langAr[i
}
;))(Language myLang=(Language)Convert.ToInt32(Console.ReadLine
;)Console.WriteLine("Your Language of choice is: " + myLang
}
}

www.Arsanjan.blogfa.com

124

Overload C#
:
Overload
Overload .
Overload
Overload
Overload C# Overload .
C#
. .

Overload
C# )
" " C# .(. C# .
.
Overload .
Overload
. .
.
Matrix struct.
) " " C# " " C# (.
Matrix
. )( Add )( Product
. :
// instance
// static

;)Matrix result = mat1.Add(mat2

;)Matrix result = Matrix.Add(mat1, mat2

Matrix result = mat1.DotProduct(mat2).DotProduct(mat3); // and so on...

www.Arsanjan.blogfa.com

125

.
. + . +
* . :
;Matrix result = mat1 + mat2
;Matrix result = mat1 * mat2
;Matrix result = mat1 * mat2 * mat3 * mat4

.
.

Overload
Overload Overload
. Overload
Overload .
. Overload
+ + .
Overload
.

Overload
C#
.
. Overload
Overload
. C# . ) (Unary Overload
:
false

--

true

++

Overload :
=<

=>

<

>

=!

==

>>

<<

&

true false
.

www.Arsanjan.blogfa.com

126

Overload C#
Overload . Overload Overload
. Overload + Overload = +
. = Overload.
Overload Overload
. /
.

Overload
Overload
operator .
.
)public static Matrix operator *(Matrix mat1, Matrix mat2
{
// dot product implementation
}

. operator
Overload Matrix .
operator Overload
. 18-1 Overload .
: 18-1 Overload
;using System
class Matrix3D
{
;public const int DIMSIZE = 3
;]private double[,] matrix = new double[DIMSIZE, DIMSIZE
// .
]public double this[int x, int y
{
} ;]get { return matrix[x, y
} ;set { matrix[x, y] = value
}
Overload +

www.Arsanjan.blogfa.com

//

127

public static Matrix3D operator +(Matrix3D mat1, Matrix3D mat2)


{
Matrix3D newMatrix = new Matrix3D();
for (int x=0; x < DIMSIZE; x++)
for (int y=0; y < DIMSIZE; y++)
newMatrix[x, y] = mat1[x, y] + mat2[x, y];
return newMatrix;
}
}
class MatrixTest
{
// . InitMatrix
public static Random rand = new Random();
static void Main()
{
Matrix3D mat1 = new Matrix3D();
Matrix3D mat2 = new Matrix3D();
// .
InitMatrix(mat1);
InitMatrix(mat2);
// .
Console.WriteLine("Matrix 1: ");
PrintMatrix(mat1);
Console.WriteLine("Matrix 2: ");
PrintMatrix(mat2);
// .
Matrix3D mat3 = mat1 + mat2;
Console.WriteLine();
Console.WriteLine("Matrix 1 + Matrix 2 = ");
PrintMatrix(mat3);
}
// .
public static void InitMatrix(Matrix3D mat)
{
for (int x=0; x < Matrix3D.DIMSIZE; x++)
for (int y=0; y < Matrix3D.DIMSIZE; y++)
mat[x, y] = rand.NextDouble();
}
// .

www.Arsanjan.blogfa.com

128

)public static void PrintMatrix(Matrix3D mat


{
;)(Console.WriteLine
)for (int x=0; x < Matrix3D.DIMSIZE; x++
{
;)" ["(Console.Write
)for (int y=0; y < Matrix3D.DIMSIZE; y++
{
// .
;)]Console.Write("{0,8:#.000000}", mat[x, y
)if ((y+1 % 2) < 3
;)" Console.Write(",
}
;)"] "(Console.WriteLine
}
;)(Console.WriteLine
}
}

18-1 + Overload .
Overload + :
)public static Matrix3D operator +(Matrix3D mat1, Matrix3D mat2
{
;)(Matrix3D newMatrix = new Matrix3D
)for (int x=0; x < DIMSIZE; x++
)for (int y=0; y < DIMSIZE; y++
;]newMatrix[x, y] = mat1[x, y] + mat2[x, y
;return newMatrix
}

.
Matrix3D operator
+ . Overload Matrix3D
.

Overload
C# Overload . Overload
.
> < ==
. > Overload => .
www.Arsanjan.blogfa.com

129

Overload .
. +
= + .

) C# ( C# 2.0


.
. .Net Framework
.

: 6 .Net Framework 2.0 C# 2.0 .


C# . :
http://csharp-persian.netfirms.com/C_Sharp_List.htm

: )(Array

Type-Safe

www.Arsanjan.blogfa.com

130

) : (List

.Net Framework Base Class


. :

:
.

.

.
.
.

www.Arsanjan.blogfa.com

131

) (Queue ) (Stack .
.Net Framework Base Class Library .
.
Hashtable
Hashtable . ) ArrayList(
(String Keys) .


.
) (Binary Search Tree
.

.
SkipList )(Linked List
.

) (Graph .
) (Nodes ) (Edge .

Egde . .

Sets Disjoined Sets Set .


Disjoined Set . Set
.
.


www.Arsanjan.blogfa.com

132


.

.
. .
.
SkipList
.
.


.
.
.


. .
:

)public bool DoesExtensionExist(string [] fileNames, string extension


{
;int i = 0
)for (i = 0; i < fileNames.Length; i++
)if (String.Compare(Path.GetExtension(fileNames[i]), extension, true) == 0
;return true

www.Arsanjan.blogfa.com

133

return false; // If we reach here, we didn't find the extension


}
}


.
) (Sort " :
n n+1
" . " " Running Time
.
. n+1

n+1 .
.

) (Asymptotic Analyze .
(Big-Oh Notation) O .
) O(n
. ) O(n
n n+1 .
O n
.

O-Notation Asymptotic Analyze


:
-1 .

.

www.Arsanjan.blogfa.com

134

.
.
-2
1 .
-3 1 1
.
.
-4

. .

.
. 2
1 . 3
n n . 3 1 n
N . ) O(n.

) O(n Asymptotic . O(log2 n),


) O(n log2 n), O(n2), O(2n .... Notation_O
.
) O(log n ) O(n . log
n<n

: loga b = y ay = b . log2 n
n n=8 log2 n = 3 n=8 .
) O(log2 n.

Asymptotic

www.Arsanjan.blogfa.com

135

Asymptotic
.
.

.
.


. ) (Sort Bubble Sort
. ) O(n2 .
Merge Sort ) O(n log2 n . Merge
Sort Bubble Sort . Bubble
Sort Merge Sort ! Merge Sort
Sort Bubble Sort
) .
Sort ( Merge Sort
Bubble Sort ) (
. Bubble Sort .
.


.
.
www.Arsanjan.blogfa.com

136

C# ) (Null .
BoolArray :
;bool[] BoolArray

;]arrayName = new arrayType[allocationSize

CLR-Managed Heap allocationSize


arrayType) . int 2
allocationSize 5 10 (. arrayType ) (Value Type
arrayType allocationSize ) . unboxed (.
arrayType ) (Reference Type arrayType
allocationSize ) . heap
.Net (.

.Net Framework :

www.Arsanjan.blogfa.com

137

;bool [] booleanArray
;FileInfo [] files

;]booleanArray = new bool[10


;]files = new FileInfo[10

booleanArray System.Boolean files


System.IO.FileInfo . CLR-Managed Heap
:

10 Files FileInfo.

www.Arsanjan.blogfa.com

138

.Net . :

// Read an array element


;]bool b = booleanArray[7
// Write to an array element
;booleanArray[0] = false

) O(1 .
.

.
.

.
.Net CLR
. IndexOutOfRangeException

www.Arsanjan.blogfa.com

139

) . 10 15
) (Bound (.
) .
C !!!

. .

(.
)) (O(1 .

:
. ) (Unmanaged Code
. "Applied
" Microsoft .Net Framework Programming Jeffrey Richter .

.
.
:

// Create an integer array with three elements


;]int [] fib = new int[3
;fib[0] = 1
;fib[1] = 1
;fib[2] = 2
// Redimension message to a 10 element array
;]int [] temp = new int[10
// Copy the fib array to temp
www.Arsanjan.blogfa.com

140

;)fib.CopyTo(temp, 0
// Assign temp to fib
;fib = temp

fib . 3 9
Int32 .


. .
) O(log n
. .Net Array )( BinarySearch
.

: .Net Framework .
) O(n k ) O(nk .
n n .


.
. Employee .
.
.
.

www.Arsanjan.blogfa.com

141

.
Employee .
Employee
Object . .Net Framework Object
.
.

Framework

.Net :

ArrayList . System.Collections.ArrayList Object


. ArrayList Object
.

ArrayList . ArrayList
Object ArrayList casting
Casting) . . )x = (int
; y y int x (.
) System.Double System.Int32 (System.Boolean
Managed Heap Unboxed . ArrayList Object .
ArrayList ArrayList
Boxed . .

www.Arsanjan.blogfa.com

142

Boxing Unboxing ArrayList


ArrayList .
ArrayList .

ArrayList .
ArrayList Object ArrayList
.
.

Generic !

ArrayList Generic .Net Framework 2.0 .


Generic .

www.Arsanjan.blogfa.com

143

.
.

public class TypeSafeList<T>


{
T[] innerArray = new T[0];
int currentSize = 0;
int capacity = 0;
public void Add(T item)
{
// see if array needs to be resized
if (currentSize == capacity)
{
// resize array
capacity = capacity == 0 ? 4 : capacity * 2; // double capacity
T[] copy = new T[capacity]; // create newly sized array
Array.Copy(innerArray, copy, currentSize); // copy over the array
innerArray = copy; // assign innerArray to the new, larger array
}
innerArray[currentSize] = item;
currentSize++;
}
public T this[int index]
{

www.Arsanjan.blogfa.com

144

get
{
if (index < 0 || index >= currentSize)
throw new IndexOutOfRangeException();
return innerArray[index];
}
set
{
if (index < 0 || index >= currentSize)
throw new IndexOutOfRangeException();
innerArray[index] = value;
}
}
public override string ToString()
{
string output = string.Empty;
for (int i = 0; i < currentSize - 1; i++)
output += innerArray[i] + ", ";
return output + innerArray[currentSize - 1];
}
}

. T TypeSafeList
.

www.Arsanjan.blogfa.com

145

T T .
. T Add T
.

T :

;TypeSafeList<type> variableName

TypeSafeList int :

;)(>TypeSafeList<int> fib = new TypeSafeList<int


;)fib.Add(1
;)fib.Add(1
)for (int i = 2; i < 25; i++
;)]fib.Add(fib[i - 2] + fib[i - 1
;))(Console.WriteLine(fib.ToString

Generics :
: Type-Safe SafeTypeList
.

: Boxing Unboxing .

: .
www.Arsanjan.blogfa.com

146

Generics
Generics
.


.
.

. .Net Framework
Sysyem.Collections.Generics .


.
) ( . Generics
.
:

// int
;)(>List<int> myFavoriteIntegers = new List<int

//
;)(>List<string> friendsNames = new List<string
www.Arsanjan.blogfa.com

147

.
.
)( Add .
. int . )( Add
.

//
;)(>List<int> powersOf2 = new List<int
6 //
;)powersOf2.Add(1
;)powersOf2.Add(2
;)powersOf2.Add(4
;)powersOf2.Add(8
;)powersOf2.Add(16
;)powersOf2.Add(32
// 10
;powersOf2[1] = 10
//
;]int sum = powersOf2[2] + powersOf2[3

.
.
. .
for .
www.Arsanjan.blogfa.com

148

)( Contains . )( IndexOf
. )( BinarySearch
. )( FindAll() Find
)( Sort )( ConvertAll delegate
.

.Net
Framework Base Class Library System.Array System.Collections.Generic.List.

. .
.

. )( Add
. )( IndexOf
. .

) (Stack ) (Queue .
. .Net Framework
Hashtable Dictionary .

www.Arsanjan.blogfa.com

149

...

:

Inheritance
Abstraction
Encapsulation
Polymorphism

C#

. ) (Component
. .
. .


.
. .

" " Attribute


Behavior .
. .
. .
3 5 .
. boolean .

.
. .

.
. :
... : .
. :
www.Arsanjan.blogfa.com

150

.
. .
.
.
. .
C# ) (Class .
. :
class Time
{
;int hours
;int minutes
;int seconds
)(void pastime
{
//some implementation
}
}

Time . class .
}{ . .
) }{( .
.
.

) (Inheritance
.
.
.
. .
.
www.Arsanjan.blogfa.com

151

.
.
. :
class Bird
{
;string beakDescription
;int wingSpan
;string typeOfBird
)(void fly
{
//some implementation
}
}

.
typeOfBird .

) (

. .
.
.
.

. ... .
.
Inheritance
. Animal .


.
Animal ""
. " " " " .

.

www.Arsanjan.blogfa.com

152

Animal -
Animal .
. : (Top-
) Down ) (Bottom-Up
.
) child( .
parent . child parent "" "" (is-a
) relationship . " ".
. ) (child
) (parent . child parent
. .

Animal Living )(Eat


. Wing )( Fly
parent . Bird
.

.
parent .
.

www.Arsanjan.blogfa.com

153

)(Abstraction
. .
Animal .
. .
.
"" ) .
) (instance . !(
Animal Bird " " " "
. Animal Bird
) .
abstract C# (.
Animal Bird
. C# .
abstract class Animal
{
//abstract definitions and implementations
}
class Bird : Animal
{
//class implementation
}

Animal abstract .
. Bird
Animal . " ": Bird
Bird Animal .

) (Encapsulation
.
. .
Encapsulation .
.
www.Arsanjan.blogfa.com

154

.
.
.
.
.
Bird . .
. .
"" . .
"" ) (has-a relationship .
" " .
. .
class Wing
{
;int foreWingSize
;int backWingSize
)(void flap
{
//implementation
}
)(void fold
{
//implementation
}
}
class Bird : Animal
{
;int beakSize
;Wing wings
)(void Fly
{
//implementation
}
}

Bird Wing . Wing . Bird


Wing wings . Bird Wing .
" " . .
Wing .
www.Arsanjan.blogfa.com

155

) (Polymorphism

.
Bird .
.
. .
.
. .
.
.
abstract class flyingBird : Bird
{
//implementation
}
class Eagle : flyingBird
{
//implementation
}
class Duck : flyingBird
{
//implementation
}
class Experiment
{
)(public static void Main
{
;]flyingBird flyingBirdCage = new flyingBird[2
;)(flyingBirdCage[0] = new Eagle
;)(flyingBirdCage[1] = new Duck
}
}

3 . flyingBird Bird .
.
Eagle Duck FlyingBird . Experiment )( Main
. )( Main flyingBirdCage FlyingBird
FlyingBird . Duck Eagle FlyingBird
.

www.Arsanjan.blogfa.com

156

.
. .
.
:
class Experiment
{
)(public static void Main
{
;)(Eagle eagleCage = new Eagle
;)(Duck duckCahge = new Duck
}
}

.
foreach
.
.

.
.

) (Polymorphism Polymorphism .
. Polymorphism C#
.
;using System
class FlyingBird
{
)(public virtual void Fly
{
;)"Console.WriteLine("This shouldn't be called
}
}
class Eagle : FlyingBird
{
)(public override void Fly
{
;)"Console.WriteLine("Eagle Fly
}
}
class Duck : FlyingBird

www.Arsanjan.blogfa.com

157

{
)(public override void Fly
{
;)"Console.WriteLine("Duck Fly
}
}
class Experiment
{
)(public static void Main
{
;]FlyingBird[] flyingBirdCage = new FlyingBird[2
;)(flyingBirdCage[0] = new Eagle
;)(flyingBirdCage[1] = new Duck
)foreach(FlyingBird bird in flyingBirdCage
{
;)(bird.Fly
}
}
}

:
Eagel Fly
Duck Fly

Eagel Duck FlyingBird . )( Fly.


. FlyingBird )( Fly virtual
.
override . )( Main foreach
. override
.

Polymorphism . Polymorphism .

www.Arsanjan.blogfa.com

158


.
SQL SQL
.
MS Access MS Office .

SQL MS SQL Server 2000 .
Visual
Studio IDE .

) MS Access (2003 ) Visual Studio .Net 2003


2002 Visual Studio .Net
2005 Visual C# Express Edition (.

Database .

. ) (DBMS
. DBMS

.

www.Arsanjan.blogfa.com

159

) (Relational .
SQL
.
Informix DB2 Sybase Oracle MS SQL Server MySQL
.

) Interface DBMS (
. C# ADO.Net .
ADO.Net
.
)(Relational Database Model

. . ) (record/row
) (columns/fields . 1
Employee . 6
number Primary Key
Primary Key . )(
. Primary Key
. Primary Key
.
Primary Key .
number . ) .
(.

. ) (Primary Key
. 3 Department
Employee 413.

www.Arsanjan.blogfa.com

160

location

salary

department

name

number

1000

413

23603

1500

413

24568

1300

642

34589

1800

611

35761

1500

413

47132

2500

611

78321


. SQL SQL .
) (SELECT
.


Book SQL .
. ) (Authors
) (Publishers ) (AuthorISBN ) (Titles . Authors
.
Authors .

authorID

. Book
int
) .(Auto-Increment Field

www.Arsanjan.blogfa.com

161


.
(string ) .

firstName

(string ) .

lastName

Authors
lastName

firstName authorID

Deitel

Harvey

Deitel

Paul

Nieto

Tem

Steinbuhler Kate

Santry

Sean

Lin

Ted

Sadhu

Praveen

McPhie

David

Yaeger

Cheryl

Zlatkina

Marina

10

Wiedermann Ben

11

Liperi

Jonathan

12

Listfield

Jeffrey

13

www.Arsanjan.blogfa.com

162

Publisher .
Publisher .

publisherID

. int
Primary Key Publisher
.

publisherName ) . (string

Publishers
publisherName publisherID
1

Prentice Hall

Prentice Hall PTG

AuthorISBN ISBN
. .
AuthorISBN .

authorID

.
. int

www.Arsanjan.blogfa.com

163

. Author
(string) . ISBN

AuthorISBN
authorID

ISBN

1 0130125075
2 0130125075
1 0130132497
2 0130132497
1 0130161438
2 0130161438
3 0130161438
1 0130284173
2 0130284173
3 0130284173
6 0130284173
7 0130284173
1 0130284181
2 0130284181
3 0130284181
8 0130284181

www.Arsanjan.blogfa.com

isbn

164

AuthorISBN
ISBN

authorID

1 013028419X
2 013028419X
3 013028419X
1 0130293636
2 0130293636

Titles ISBN
. .


isbn

ISBN (string) .

title

(string) .

editionNumber )(string
copyright
publisherID

)(int
) .(int
Publisher .

imageFile
price

(string) .
) . (

Titles
www.Arsanjan.blogfa.com

165

Book . .
Bold Primary Key .
Primary Key

Primary Key . "


" ) .(Rule Of Entity Integrity AuthorISBN
Primary Key Primary Key
authorID isbn ) ( .
authorID 2 authorID isbn
authorID isbn .
isbn 0130895601
authorID 2 isbn 0130895601.

: Primary Key DBMS


.

: Primary Key DBMS .

) (Relationship .
Publisher Titles . Publisher 1
Titles )( . " "
www.Arsanjan.blogfa.com

166

) (One-to-Many Publishers
Titles . publisherID
Publisher publisherID Titles . publisherID Titles
Foreign Key
Primary Key Foreign Key .
. Foreign Key " " ) (Rule Of Referential Integrity
Foreign Key Primary Key .
Foreign Key "" ) (join .
" " Primary Key Foreign Key Foreign Key
Primary Key .

: " " Primary Key Foreign Key


.

: Foreign Key Primary Key


DBMS .

)(SQL

SQL . SQL
.

SQL

SELECT

FROM

www.Arsanjan.blogfa.com

167

. SELECT DELETE .
WHERE
INNER JOIN

.

.

GROUP BY

ORDER BY

INSERT

UPDATE

) . (

DELETE

SELECT

SQL .
SELECT :
SELECT * FROM tableName

"*" ) (
tableName .
SELECT * FROM Authors

SELECT
* " ", .

www.Arsanjan.blogfa.com

168

SELECT authorID, lastName FROM Authors

authorID lastName Authors .

: ) (Space "]["
(SELECT [author ID] FROM Authors) .
WHERE

.
SQL . WHERE SELECT
. SELECT WHERE :
SELECT fieldName1,fieldName2, FROM tableName
WHERE criteria

fieldName tableName
criteria .
1999 SELECT :

SELECT title
FROM Titles
WHERE copyright > 1999

: C# SQL )(Query
. SQL .
www.Arsanjan.blogfa.com

169

WHERE > <> = >= <= < LIKE . LIKE " "
) (Pattern Matching * ? .
. query
Authors lastName " "D :

SELECT * FROM Authors


'*WHERE lastName LIKE 'D

* D
. D
D .

: LIKE .
: "*" LIKE " "% .
: Case Sensitive .
: SQL .

"?"
"?" . query Authors
lastName " "i
:

SELECT * FROM Authors


'*WHERE lastName LIKE '?i
www.Arsanjan.blogfa.com

170

: "?" "_" LIKE .


: LIKE ' ' .

ORDER BY

query . ORDER BY .
:

SELECT fieldName1, fieldName2, FROM tableName


ORDER BY field ASC

SELECT fieldName1, fieldName2, FROM tableName


ORDER BY field DESC

field query .
ASC DESC .
query .
SELECT * FROM Authors
ORDER BY lastName DESC

ORDER BY query :
ORDER BY field1 sortingOrder, field2 sortingOrder,

www.Arsanjan.blogfa.com

171

field sortingOrder
.
. query
) (lastName ) (firstName :
SELECT * FROM Authors
ORDER BY lastName, firstName

query WHERE ORDER BY :

SELECT isbn, title, price FROM Titles


'WHERE title LIKE '%How To Program
ORDER BY title DESC

INNER JOIN :


. Book Authors Titles .
AuthorISBN .
Titles

.

. " "
INNER JOIN SELECT SQL . INNER JOIN

. INNER JOIN :

www.Arsanjan.blogfa.com

172

SELECT fieldName1, fieldName2,


FROM table1
INNER JOIN table2
ON table1.fieldName = table2.fieldName

ON
. query ISBN
:

SELECT firstName, lastName, isbn


FROM Authors
INNER JOIN AuthorISBN
ON Authors.authorID = AuthorISBN.authorID
ORDER BY lastName, firstName

query firstName lastName Authors isbn AuthorISBN


lastName firstName . query
ON tableName.fieldName .
. " "tableName.
.

Titles AuthorISBN Authors Publisher

Book query ISBN


.

www.Arsanjan.blogfa.com

173

query . query
: query .

SELECT
Titles.Title,
Titles.ISBN,
Authors.LastName, Publishers.PublisherName

Authors.FirstName,

FROM
(
Publishers
INNER JOIN Titles
ON Publishers.PublisherID = Titles.PublisherID
)
INNER JOIN
(
Authors
INNER JOIN AuthorISBN
ON Authors.AuthorID = AuthorISBN.AuthorID
)

ON Titles.ISBN = AuthorISBN.ISBN
ORDER BY Titles.Title;

www.Arsanjan.blogfa.com

174

query :

query

query . 1 2 query
.
. query title isbn Titles
lastName firstName Authors copyright Titles publisherName
Publishers . query
) . Fully Qualified Name (.
. query INNER JOIN . INNER JOIN
INNER JOIN
INNER JOIN .
. :
(Publishers INNER JOIN Titles
)ON Publishers.publisherID = Titles.publisherID

Publishers Titles publisherID


. INNER JOIN
.
INNET JOIN query :

( Authors
INNER JOIN AuthorISBN
) ON Authors.AuthorID = AuthorISBN.AuthorID

www.Arsanjan.blogfa.com

175

Authors AuthorISBN AuthorID .


INNER JOIN query :

(
Publishers
INNER JOIN Titles
ON Publishers.PublisherID = Titles.PublisherID
)
INNER JOIN
(
Authors
INNER JOIN AuthorISBN
ON Authors.AuthorID = AuthorISBN.AuthorID
)

ON Titles.ISBN = AuthorISBN.ISBN

INNER JOIN Titles.isbn


AuthorISBN.isbn .
INNER JOIN .
query Titles.title .

INSERT

www.Arsanjan.blogfa.com

176

. :

) INSERT INTO tableName (fieldName1, fieldName2,


) VALUES (value1, value2,

tableName . tableName
VALUES . fieldName
value . value
field . fieldName1 firstName
value1
' ' . query :

)INSER INTO Authors (lastName, firstName


)'VALUES ('Smith' , 'Sue

query Authors . INSERT


Primary Key Primary Key authorID
auto-increment
. Primary Key
INSERT ) (Null .

SQL : ' ' . '


) (O'Reily ' 'O' 'Reily .

UPDATE

177

:
UPDATE tableName
SET fieldName1 = value1, fieldName2 = value2,
WHERE criteria

fieldName ) (value
. WHERE UPDATE
. :

UPDATE Authors
'SET lastName = 'Jones
'WHERE lastName = 'Smith' AND firstName = 'Sue

Sue Smith Sue Jones .

: WHERE UPDATE .

DELETE

DELETE :

DELETE FROM tableName


WHERE criteria

178

criteria .

DELETE FROM Authors


'WHERE lastName = 'Jones' AND firstName = 'Sue

Sue Jones.

: WHERE DELETE
WHERE
.

(ADO.Net Object Model) ADO.NET

ADO.Net API
ADO.Net . .Net Framework ADO) . ADO
ActiveX Data Objects(.

System.Data .Net Framework API ADO.Net .


Namespace ADO.Net System.Data.OleDb System.Data.SqlClient
Data Source ) . Data Source
(.
System.Data.OleDb Data Source
System.Data.SqlClient MS SQL Server 2000.

179

ADO.Net MS Access

Access
MS Office .
.

Access System.Data.OleDb .
:

Access OleDbConnection .
connection string
. Access
connection string . :

= string connectionString
"provider=Microsoft.Jet.OLEDB.4.0;" +
;""data source=F:\\Samples\\Books.mdb

connection string Access .


provider Access

180

Microsoft.Jet.OLEDB.4.0 data source ) .


(.
"\\" "\" .

Access
OledbConnection .

;using System
;using System.Data
;using System.Data.OleDb

class OleDbConnectionAccess
{
)(public static void Main
{
// .
= string connectionString
"provider=Microsoft.Jet.OLEDB.4.0;" +
"data
;"source=F:\\Samples\\Books.mdb

OleDbConnection //
connectionString //.
= OleDbConnection myOleDbConnection
;)new OleDbConnection(connectionString

181

// OleDbCommand
OleDbCommand myOleDbCommand =
myOleDbConnection.CreateCommand();

// SQL OleDbCommand CommandText


//. Authors
myOleDbCommand.CommandText =
"SELECT * "+
"FROM Authors "+
"WHERE authorID=1";

// Open()
myOleDbConnection.Open();

// ExecuteReader() OleDbDataReader
// SELECT OleDbCommand
OleDbDataReader myOleDbDataReader =
myOleDbCommand.ExecuteReader();

// OleDbDataReader
// Read()
myOleDbDataReader.Read();

182

//
Console.WriteLine("myOleDbDataReader[\" firstName\"] = "+
myOleDbDataReader["firstName"]);
Console.WriteLine("myOleDbDataReader[\" lastName\"] = "+
myOleDbDataReader["lastName"]);
Console.WriteLine("myOleDbDataReader[\" AuthorID\"] = "+
myOleDbDataReader["authorID"]);

// Close() OleDbDataReader
myOleDbDataReader.Close();

// OleDbConnection
myOleDbConnection.Close();
}
}

:
myOleDbDataReader[" firstName"] = Harvey
myOleDbDataReader[" lastName"] = Deitel
myOleDbDataReader[" AuthorID"] = 1

SQL
.

183

You might also like