Anda di halaman 1dari 26

c 

    



1.Y  .NET By CRE Innovations
2.Y What is  .NET?
Y  .NET is the feature in .NET that allows you to interact with database.
Y  .NET is the successor of   ± ctive ata bjects but its
implementation is totally done in .NET and it is no longer an upgrade of  .
Y The classes used for  .NET are available in System. ata dll and
System. ata.racleClient dll.
Y 0sing these  .NET features you can insert, update, delete, select records from
tables, execute stored procedures.

pplication  .NET atabase

3.Y dvantages of  .NET


Y The following are the advantages of using  .NET.
Y isconnected data architecture: Most of the information about the data is
available offline. For example: Tables, relationship, constraints.
Y ML: Every piece of data can be exported to ML format and the information
about the data is also stored in ML.
Y Inter-operable: ata from different data sources can be integrated easily to the
application and can even be manipulated in the same way because of ML.
Y Native rivers: Specific drivers to connect to database. ll native to the .NET
Framework i.e drivers are developed in .net or interact safely from managed
environment.
4.Y M C
Y Microsoft ata ccess Components are set of libraries shipped with windows.
Y 2.8 version of M C must be installed in the system to interact with some
databases.
Y Next slide explains how data is obtained from different sources.
5.Y Interaction with atabase SQL Server SqlClient racle Server racleClient ccess /
Excel le b Text File & thers  BC M C M C
6.Y  .NET namespace chart SqlClient racleClient le b  BC System. ata
Y SqlConnection
Y SqlCommand
Y SqlParameter
Y Sql ataReader
Y Sql atadapter
Y Sql bType
Y SqlTransaction
Y racleConnection
Y racleCommand
Y racleParameter
Y racle ataReader
Y racle atadapter
Y racle bType
Y racleTransaction
Y le bConnection
Y le bCommand
Y le bParameter
Y le b ataReader
Y le b atadapter
Y le b bType
Y le bTransaction
Y dbcConnection
Y dbcCommand
Y dbcParameter
Y dbc ataReader
Y dbc atadapter
Y dbc bType
Y dbcTransaction

ataSet

7.Y ata Set


Y This is the most important object in  .NET and plays a key role in
disconnected data architecture.
Y This object holds the data in tables, relationship between tables, constraints and
enforces these constraints even when the connection to the database is not alive.
Y In short it can be described as a mini database available to the application offline.
Y The data set is filled with data and addition details through the data adapter.
Y ata in data set can be exported to ML.
Y ataset
åY ataTable
åY ataRow
åY ataColumn
åY ataView
åY ataRelation
8.Y SQL Connection
Y The first step in getting data from database is connecting to the database.
Y using System. ata; //Namespace declaration.
Y using System. ata.SqlClient;
Y The following is the code sample to open a new connection in SQL Server.
Y SQL Client  .NET 2.0 supports MRS ± Multiple ctive Result Set. 
MRS enabled connection can be used to execute multiple commands using the
same connection.
Y  connection string for SQL Server will look like this

SqlConnection objSqlConn = new SqlConnection(); objSqlConn.ConnectionString =


³connection string´; objSqlConn.pen();
Server=myServerddress; atabase=my ataBase;0id=my0sername;Pwd=myPassword;
http://www.connectionstrings.com/
´.Y SQL Command
Y The second step in getting data from database is to define the command, its
parameters to be executed in the database.
Y SqlCommand object is used for this.
Y The following is the code sample to initialize the command object.
Y The important methods of Sql Command object are:
åY ExecuteScalar: Returns the value of first row, first column.
åY ExecuteNonQuery: Returns the number of rows affected.
åY ExecuteReader: Returns result in Sql ataReader.

SqlCommand objSqlCmd = new SqlCommand(); objSqlCmd.CommandText = ³SP


name´; objSqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.Parameters.dd( "@Name" , Sql bType .VarChar).Value =
"CRE´ ; SqlCmd.Connection = objSqlConn;

10.YSQL ata Reader


Y The final step in getting data from database is to define the object in which you
want the data.
Y ata from database can be stored in Sql ataReader, ataTable, ataSet.
Y Sql ataReader is a forward read only object that holds the data from database.
Y This is used in places where the data is to be read only once and it gives good
performance.
Y Sql ataReader needs an open connection while accessing the data in it.
Y Important properties and methods of Sql ataReader
åY ùasRows ± is a boolean flag specifying if the reader has any rows
in it.
åY FieldCount ± Specifies the number of columns present in the
current row of data reader.
åY Read ± peration to get the next row from data reader. If no row is
left it returns false.
11.YSQL ata dapter
Y ata adapter is used to fill the data into dataset or data table.
Y ata adapter is the channel through which you can retrieve the data from database
and do operations like insert, update and delete.
Y The following are the key properties and operations of Sql atadapter.
åY Fill ± peration to execute select command and fill the
dataset/datatable.
åY SelectCommand ±  SqlCommand object which has select query
in it.
åY 0pdateCommand ±  SqlCommand object which has update query
in it.
åY InsertCommand ±  SqlCommand object which has insert query in
it.
åY eleteCommand ±  SqlCommand object which has delete query
in it.
0pdate ± This operation performs the insert/update/delete
åY
operation on the dataset i.e it updates data in database from dataset,
inserts new data to database from dataset, deletes data in database
based on records deleted in the dataset. In short it is a
synchronization operation performed by adapter.
12.YCRE Innovations Thank you

Y
Y
Ñ 
Today we will learn the language fundamentals of C#. We will explore the data types in C#,
using variables, operators, flow control statements like if.. else, looping structure and how to use
arrays.


c   o
There are two kinds of data types in C#.

Y Value Types (implicit data types, structs and enumeration)


Y Reference Types (objects, delegates)

Value types are passed to methods by passing an exact copy while Reference types are passed to
methods by passing only their reference (handle). Implicit data types are defined in the language
core by the language vendor, while explicit data types are types that are made by using or
composing implicit data types.

s we saw in the first issue, implicit data types in .Net compliant languages are mapped to types
in the Common Type System (CTS) and CLS (Common Language Specification). ùence, each
implicit data type in C# has its corresponding .Net type. The implicit data types in C# are:
6 
      
 Y
YYYYYYYYYYYYYYYYYY 
 Y
 Y Y Y Y
  YYYYYY  YYYYYYYYYYYYYYY 
 YY
Y
Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY    Y Y
Y
Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY 
Y Y  Y YY
’  Y
 YYYYYY YYYYYYYYYYYYYYYY 
Y
  Y YY
 YYYYY YYYYYYYYYYYYYY
Y  Y YY Y Y
 YYYYY! "YYYYYYYYYYYYYY# Y Y$% "Y Y$% " Y
  YYYY! "YYYYYYYYYYYYY
%Y  Y YY Y"%$Y

 YYYYYYY! $YYYYYYYYY&YYYYY# Y Y%& %&$%"&Y Y


X 'YYYYYYYYYYYYYYYYYYYYY%& %&$%"& Y

 YYYYYY! $YYYYYYYY&YYYYY
%Y  Y YY Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY&%(&%(" %(Y
YYYYYY! "&YYYYYYYYYYYYYY# Y Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY(%$%$ %$"%&% %Y Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY(%$%$ %$"%&% % Y
YYYYY! "&YYYYYYYYYYYYY
%Y  Y YY Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY%&&"% &&% $% (%%"Y
º   Y
 YYYYY
YYYYYYYY&YYYYY# Y Y)*Y+Y&Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY Y)$*&Y+Y$Y,
Y Y

Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY- 

*Y#
 Y Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY 
.YY Y/Y
 YYYY0 YYYYYYYYYYYYY# Y Y)*Y+Y$&Y Y
X 'YYYYYYYYYYYYYYYYYYYYY)* Y+Y$Y,
Y"Y

Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY- 

Y
Y

YYY0
YYYYYYYYYYY# Y Y*Y+YY Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY *(Y+YY,
Y(Y

Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY- 

*Y#
 Y Y
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY 
.YY YY

Implicit data types are represented in language using keywords, so each of the above is a
keyword in C# (Keyword are the words defined by the language and can not be used as
identifiers). It is worth noting that string is also an implicit data type in C#, so
 is a
keyword in C#. The last point about implicit data types is that they are value types and thus
stored on the stack, while user defined types or referenced types are stored using the heap. 
stack is a data structure that store items in a list in first out (LIF) fashion. It is an area of
memory supported by the u  and its size is determined at the compile time.  heap
consists of memory available to the program at run time. Reference types are allocated using
memory available from the heap dynamically (during the execution of program). The garbage
collector searches for non-referenced data in heap during the execution of program and returns
that space to perating System.

ü 
uring the execution of a program, data is temporarily stored in memory.  variable is the name
given to a memory location holding a particular type of data. So, each variable has associated
with it a data type and a value. In C#, variables are declared as:
YYYY1 Y -2Y13
 24Y
e.g.,
YYYY
 Y
4Y

The above line will reserve an area of 4 bytes in memory to store an integer type values, which
will be referred to in the rest of program by the identifier 'i'. You can initialize the variable as
you declare it (on the fly) and can also declare/initialize multiple variables of the same type in a
single statement, e.g.,
YYYY YY
#YYYYYY5Y 4Y
YYYY Y-  YYY5Y *%Y3 Y5Y&$*(4Y
YYYY  YY

YYYYYYYY5Y 4Y

In C# (like other modern languages), you must declare variables before using them. lso, there is
the concept of " efinite ssignment" in C# which says "local variables (variables defined in a
method) must be initialized before being used". The following program won't compile:
YYYY 
Y3
Y
X'Y
YYYY6Y
YYYYYYYY
 Y4YYYYYYYYYYYYY
YYYYYYYY77YY5Y4Y
YYYYYYYY *8
9
X'4YYYY77Y  Y
YYYY:Y

But, if you un-comment the 2nd line, the program will compile. C# does not assign default
values to local variables. C# is also a type safe language, i.e., values of particular data type can
only be stored in their respective (or compatible) data type. You can't store integer values in
Boolean data types like we used to do in C/C++.

ü  


Constants are variables whose values, once defined, can not be changed by the program.
Constant variables are declared using the  è  , like:
YYYY Y Y;!Y5Y$*&4Y

Constant variables must be initialized as they are declared. It is a syntax error to write:
YYYY Y
 Y<#=4Y

It is conventional to use capital letters when naming constant variables.

    


£   suggests using   (first letter in lowercase) for variables and 

  (first letter in uppercase) for methods. Each word after the first word in the name of
both variables and methods should start with a capital letter. For example, variable names
following Camel notation could be:
 YYYYYYYYYYYY   Y
   YYYYYY
;
Y
Some typical names of method following Pacal Notation are
d > X'YYYYYYYYYYYY  X'Y
8
9
X'YYYYYYYYYYY9 !.?X'Y

lthough it is not mandatory to follow this convention, it is highly recommended that you
strictly follow the convention. Microsoft no longer supports ùungarian notation, like using
iMarks for integer variable. lso, using the underscore _ in identifiers is not encouraged.

   


   
Several common arithmetic operators are allowed in C#.
‘      Y
@YYYYYYYYYX'Y
YYYYYYYYYX   'Y
AYYYYYYYYYX
-'Y
7YYYYYYYYYX
3
'Y
BYYYYYYYYYX 
 Y Y'Y
@@YYYYYYYYX
  Y Y'Y
YYYYYYYYX  Y Y'Y
Y

Y


Y 4Y
 -Y  - Y
6Y
YYYY Y<

?-   Y
YYYY6Y
YYYYYYYY77Y> Y-  Y , Y Y YY

Y-   YY
YYY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8
9
Y
YYYYYYYYYYYYYYX Y5Y6:%YY5Y6: %Y%Y'4Y
YYYYYYYY:Y
YYYY:Y
:Y
lthough the program above is quite simple, I would like to discuss some concepts here. In the
 *8
9
X' method, we have used format-specifiers 6
 : to indicate the position of
variables in the string.
YYYY *8
9
Y
YYYYYYX YY6:YY6:Y
Y6: %Y
YYYYYY%Y%Y '4Y

ùere, 6:, 6: and 6: will be replaced by the values of the ,  and  variables. In
6
:,
specifies that (i+1)th variable after double quotes will replace it when printed to the
Console. ùence, 6: will be replaced by the first one, 6: will be replaced by the second
variable and so on...

nother point to note is that num1++ has the same meaning as:
YYYYY5YY@Y4Y
or,
YYYYY@5Y4Y
Y

 !  ! 


Both the ++ and -± operators can be used as prefix or postfix operators. In prefix form:
YYYYY5Y$4Y
YYYYY5Y@@4YYY77YY5Y&%YY5Y&Y
The compiler will first increment num1 by 1 and then will assign it to num2. While in postfix
form:
YYYYY5Y@@4YYY77YY5Y&%YY5Y$Y

The compiler will first assign num1 to num2 and then increment num1 by 1.

    
ssignment operators are used to assign values to variables. Common assignment operators in
C# are:
‘      Y
5YYYYYYYYYX
-Y
 'Y
@5YYYYYYYYX

3Y
 'Y
5YYYYYYYYX  
3Y
 'Y
A5YYYYYYYYX
-

3Y
 'Y
75YYYYYYYYX
3

Y
 'Y
B5YYYYYYYYXY
 'Y

The equals (=) operator is used to assign a value to an object. Like we have seen
YYYY YYYY
;
Y5Y 4Y

assigns the value 'false' to the isPaid variable of Boolean type. The left hand and right hand side
of the equal or any other assignment operator must be compatible, otherwise the compiler will
complain about a syntax error. Sometimes casting is used for type conversion, e.g., to convert
and store a value in a variable of type double to a variable of type int, we need to apply an
integer cast.
YYYY YY CY5Y&*" 4Y
YYYY77Y
 CY,
Y YY Y&Y
YYYY
 YYYYY
 CYYYY5YX
 'Y C4Y

f course, when casting there is always a danger of some loss of precision; in the case above, we
only got the 4 of the original 4.67. Sometimes, the casting may result in strange values:
YYYY
 YYYYYY
 CYYYY5Y$4Y
YYYY  YY  CYYYY5YX  'Y
 C4YYYYY
YYYY77Y  CY,Y YY Y$ $"Y

Variables of type short can only take values ranging from -32768 to 32767, so the cast above can
not assign 32800 to  C. ùence  C took the last 16 bits (as a short consists of
16 bits) of the integer 32800, which gives the value -32736 (since bit 16, which represents the
value 32768 in an int, now represents -32768).

If you try to cast incompatible types like:


YYYY YYY
;
YYYYYY5Y 4Y
YYYY
 YYYY
 CYYYY5YX
 'Y
;
4Y

It won't get compiled and the compiler will generate a syntax error.

M    


Relational operators are used for comparison purposes in conditional statements. Common
relational operators in C# are:
‘      Y
55YYYYYYYYX
Y 'Y
D5YYYYYYYYX
Y 'Y
2YYYYYYYYYX   Y 'Y
1YYYYYYYYYX Y 'Y
25YYYYYYYYX   Y Y YY 'Y
15YYYYYYYYX Y Y YY 'Y

Relational operators always result in a Boolean statement; either true or false. For example if we
have two variables
YYYY
 YY5Y%YY5Y"4Y
then,
YYYYY55YYY77Y Y
YYYYYD5YYY77Y Y
YYYYY2YYYY77Y Y
YYYYY1YYYY77Y Y
YYYYY15YYY77Y Y
YYYYY25YYY77Y Y

nly compatible data types can be compared. It is invalid to compare a  with an
 , so if
you have
YYYY
 YYYYY
Y5Y4Y
YYYY YYYY Y5Y 4Y

you cannot compare i and b for equality (i==b). Trying to do so will result in a syntax error.

Ñ
 "    
These operators are used for logical and bitwise calculations. Common logical and bitwise
operators in C# are:
‘      Y
EYYYYYYYYYX
,
Y<F0'Y
±YYYYYYYYYX
,
Y?#'Y
GYYYYYYYYYX
,
YH?#'Y
DYYYYYYYYYX
,
YF?>'Y
EEYYYYYYYYX 9
 Y Y  Y

Y<F0'Y
±±YYYYYYYYX 9
 Y Y  Y

Y?#'Y

The operators &, | and ^ are rarely used in usual programming practice. The NT operator is
used to negate a Boolean or bitwise expression like:
YYYY YYYY YYYYY5Y 4Y
YYYY YYYY YYYY5YD 4Y
YYYY77Y Y,Y Y Y

Logical perators && and || are used to combine comparisons like


YYYY
 YY
5"%YI54Y
YYYY Y
C YY5Y
2$YEEYI14Y
YYYY77Y
C Y,Y Y Y
YYYY Y C Y5Y
2$Y±±YI14Y
YYYY77Y C Y,Y Y Y

In the first comparison:


2$YEEYI1 will result in true only if  the conditions
2$ and I1
result in true.
In the second comparison:
2$Y±±YI1 will result in true if  of the conditions
2$ and I1
result in true. You can, of course, use both && and || in single statement like:
YYYY Y
C YYYY5Y
YYYYYX
2$YEEYI1'Y±±YX
1 YEEYI2'Y
YYYYYY77Y
C Y,Y Y Y

In the above statement we used paranthesis to group our conditional expressions and to avoid
any ambiguity.

You can use & and | operators in place of && and || but for combining conditional expressions,
&& and || are more efficient because they use "short circuit evaluation". For example, if in the
expression X
2$YEEYI1',
2$ evaluates to false, the second expression I1 won't be checked
and false will be returned (when using N , if one of the participant operands is false, the whole
operation will result in false). ùence, one should be very careful when using assignment
expressions with && and || operators. The & and | operators don't do short circuit evaluation and
do execute all the comparisons before returning the result.

    
There are some other operators present in C#.  short description of these is given below:
‘      Y
11YYYYYYYYX Y
 Y
,
Y-   'Y
22YYYYYYYYX
 Y
 Y
,
Y-   'Y
*YYYYYYYYYX  Y Y Y I 'Y
JKYYYYYYYYX
.
Y-   Y Y
Y
YYYYYYYYYYYY  YY
 'Y
X'YYYYYYYYX Y-   'Y
LMYYYYYYYYX   Y-   'Y

   


ll operators are not treated equally. There is a concept of "operator precedence" in C#. For
example:
YYYY
 Y
Y5YY@Y$YAY"4Y
YYYY77Y
Y,Y YY Y$Y

3 will be multiplied by 6 first then the result will be added to 2. This is because the multiplication
operator * has precedence over the addition operator +. For a complete table of operator
precedence, consult MS N or the .Net framework documentation.

º"    


Condition checking has always been the most important construct in any language right from the
time of the assembly language days. C# provides conditional statements in the form of the
if...else statement. The structure of this statement is:
YYYY
XY.- 
'Y
YYYYYYYY   Y Y YY   Y
YYYY Y
YYYYYYYY   Y Y YY   Y

The else clause above is optional.  typical example is:


YYYY
X
55'Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX > Yd%Y!Y
Y Y* '4Y

In the above example, the console message will be printed only if the expression i==5 evaluates
to true. If you would like to take some action when the condition does not evaluate to true, then
you can use else clause:
YYYY
X
55'Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX > Yd%Y!Y
Y Y* '4Y
YYYY Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX 
***8 Y,
Y!Y YL '4Y

nly the first message will be printed if i is equal to 5. In any other case (when i is not 5), the
second message will be printed. If you want to use a block of statements (more than one
statement) under if or else, you can enclose your block in {} brackets:
YYYY
X
55'Y
YYYY6Y
YYYYYYYYIY5Y
A4Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX > Yd%Y!Y
Y Y* '4Y
YYYY:Y
YYYY Y
YYYY6Y
YYYYYYYYIY5Y
74Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX 
***8 Y,
Y!Y YL '4Y
YYYY:Y
I would always recommend to use { } brackets to enclose the statements following if and else
even if you only have a single statement. It increases readability and prevents many bugs that
otherwise can result if you neglect the scope of if and else statements.

You can also have if after else for further conditioning:


YYYY
X
55'YYYYYYYY77Y
YY
YYYY6Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX > Yd%Y!Y
Y Y* '4Y
YYYY:Y
YYYY Y
X
55"'YYYY77Y
YY
YYYY6Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX ?%Y"Y
Y Y Y* '4Y
YYYY:Y
YYYY YYYYYYYYYYYY77Y
Y(Y
YYYY6Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX 
***8 Y,
Y!Y Y
YYYYYYYYYYY Y Y Y YL '4Y
YYYY:Y

ùere  Y
X
55"' is executed only if the first condition
55 is false, and else at line ´ will
be executed only if the second condition
55" (line 5) executes and fails (that is, both the first
and second conditions fail). The point here is   at line ´ is related to
 on line 5.

Since
***  is also an statement, you can use it under other if...else statement (nesting),
like:
YYYY
X
2'YYYYYYYYY77Y
YY
YYYY6Y
YYYYYYYY
X
55"'YYYY77Y
Y$Y
YYYYYYYY6Y
YYYYYYYYYYYY *8
9
Y
YYYYYYYYYYYYYYX ?%Y"Y
Y Y Y* '4Y
YYYYYYYY:Y
YYYYYYYY YYYYYYYY77Y
Y Y
YYYYYYYY6Y
YYYYYYYYYYYY *8
9
Y
YYYYYYYYYYYYYYX ?- DY!Y Y YY  Y Y"D '4Y
YYYYYYYY:Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX > Yd%Y!Y
Y Y Y Y* '4Y
YYYY:Y
YYYY YYYYYYYYYYYY77Y
Y$Y
YYYY6Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX 
***8 Y,
Y!Y Y
YYYYYYYYYYY Y Y YL '4Y
YYYY:Y

The   on line 7 is clearly related to


 on line 3 while   on line 13 belongs to
 on line
1. Finally, do note (C/C++ u    especially) that
 statements expect only Boolean
expressions and not integer values. It's an error to write:
YYYY
 YY5Y4Y
YYYY
XY5Y'Y
YYYY6Y
YYYYYYYY77YY 
***Y
YYYY:Y

Instead, you can either use:


YYYY
 YY5Y4Y
YYYY
XY55Y'YYYY77Y Y55Y
YYYY6Y
YYYYYYYY77YY 
***Y
YYYY:Y
or,
YYYY YY5Y 4Y
YYYY
XY5Y 'YYYY77YY.- 
Y
YYYY6Y
YYYYYYYY77YY 
***Y
YYYY:Y

The keys to avoiding confusion in the use of any complex combination of


***  are:

Y ùabit of using {} brackets with every


 and  .
Y Indentation: aligning the code to enhance readability. If you are using Visual Studio.Net
or some other editor that supports coding, the editor will do indentation for you.
therwise, you have to take care of this yourself.
I strongly recommend you follow the above two guidelines, or that you do not use if...else
statements at all.

" 


If you need to perform a series of specific checks, ,
 ***  is present in C# just for this.
The general structure of the ,
 ***  statement is:
YYYY ,
 X
  Y Y
Y.- 
'Y
YYYY6Y
YYYYYYYY Y  .- 
MY
YYYYYYYYYYYY   Y
YYYYYYYYYYYY 
Y YI-Y   Y
YYYYYYYY77Y Y  Y Y  Y
YYYYYYYY***Y
YYYYYYYY MY
YYYYYYYYYYYY   Y
YYYYYYYYYYYY 
Y YI-Y   Y
YYY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YYY
Y  '4Y
YYYYYYYYYYYYYYYYYYYY 4YYYYY77Y Y YY ,
 Y Y
YYYYYYYYYYYYYYYY MYYYYYYY77Y
Y
Y
Y YYY Y 3Y
YYYYYYYYYYYYYYYYYYYY *8
9
Y
YYYYYYYYYYYYYYYYYYYYYYX Y -YY  Y  Y Y%YYY$ '4Y
YYYYYYYYYYYYYYYYYYYY 4YYYYY77Y Y YY ,
 Y Y
YYYYYYYYYYYY:Y
YYYYYYYY:Y
YYYY:Y
:Y

The program must be supplied with an integer command line argument. First, compile the
program (at the command line or in Visual Studio.Net). Suppose we made an exe with name
"SwitchCaseExample.exe", we would run it at the command line like this:
YYYYM2,
  N.-YY
YYYYY -YYX ,'Y YY
Y  Y
or,
YYYYM2,
  N.-Y$&Y
YYYYY -YY  Y  Y Y%YYY$Y

If you did not enter any command line arguments or gave a non-integer argument, the program
will raise an exception:
YYYYM2,
  N.-Y
 YN.-
MY *!.? ?#N.-
MY
YY!.Y, Y
Y Y  YY Y *Y
YYY Y  - *,
  N.-*
Y
YYYYX
JKY  !- 'Y
YY
YYYMO3
Y 
Y- I O,
  N.-OY
YYYYY,
  N.-* YM
Y(Y

Let's get to internal working. First, we converted the first command line argument
(  !- JK) into an
 variable
- . For conversion, we used the static ; X' method
of the
 data type. This method takes a
 and returns the equivalent integer or raises an
exception if it can't. Next we checked the value of input variable using a switch statement:
YYYY ,
 X
- 'Y
YYYY6Y
YYYY***Y
YYYY:Y

Later, on the basis of the value of input, we took specific actions under respective case
statements. nce our case specific statements end, we mark it with the break statement before
the start of another case (or the default) block.
YYYY Y$MYYYYYYY77Y
Y
Y
Y$Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX Y -Y$YX 'Y Y
Y
YYYYYYYYYYY
Y  '4Y
YYYYYYYY 4YYYY77Y Y YY ,
 Y Y

If all the specific checks fail (input is none of 1,2 and 3), the statements under  executes.

default: // if it is not any of the above Console.WriteLine ("You typed a number other than 1, 2
and 3"); break; // get out of switch block

There are some important points to remember when using the switch...case statement in C#:

Y You can use either integers (enumeration) or strings in a switch statement


Y The expression following case must be constant. It is illegal to use a variable after case:

YYYY Y
MYYYYYYYY77Y
  %Y  .Y  Y

Y  colon : is used after the case statement and not a semicolon ;


Y You can use multiple statements under single case and default statements:

YYYY Y ;
 MY
YYYYYYYY
 Y5Y <
 4Y
YYYYYYYY *8
9
X ;
Y
YY<
Y  '4Y
YYYYYYYY 4Y
YYYY MY
YYYYYYYY
 Y5Y  
P 4Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX  
PY Y
3  '4Y
YYYYYYYY 4Y

Y The end of the case and default statements is marked with  (or  ) statement. We
don't use 6: brackets to mark the block in ,
 ***  as we usually do in C#
Y C# does not allow fall-through. So, you can't leave   or  without 
statement (as you can in Java or C/C++). The compiler will detect and complain about
the use of fall-through in the ,
 ***  statement.
Y The  statement transfers the execution control out of the current block.
Y Statements under  will be executed if and only if all the case checks fail.
Y It is not necessary to place  at the end of ,
 ***  statement. You can
even place the default block before the first case or in between cases;  will work
the same regardless of its position. ùowever, making  the last block is
conventional and highly recommended. f course, you can't have more than one 
block in a single ,
 *** .

Ñ#
Loops are used for iteration purposes, i.e., doing a task multiple times (usually until a
termination condition is met)

 Ñ
The most common type of loop in C# is the for loop. The basic structure of a  loop is exactly
the same as in Java and C/C++ and is:
YYYY X
 4Y

4Y
  7  'Y
YYYYYYYY   Y Y YY   Y
YYYYYYYY Y
Y6:Y  Y

Lets see a  loop that will write the integers from 1 to 10 to the console:
YYYY X
 Y
54Y
154Y
@@'Y
YYYY6Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX !Y Y-%Y Y3YY
Y
Y6:* %Y
'4Y
YYYY:Y

t the start, the integer variable i is initialized with the value of 1. The statements in the for loop
are executed while the condition (i<=10) remains true. The value of i is incremented (i++) by 1
each time the loop starts.

Some important points about the for loop are:


ll three statements in for(), assignment, condition and increment/decrement are optional. You
can use any combination of these and even decide not to use any one at all .This would make
what is called and 'Indefinite or infinite loop' (a loop that will never end until or unless ed
inside the body of the loop). But, you still have to supply the appropriate semi colons:
 X4Y4'Y
 XY4Y
14Y
@@'Y
 X
 Y
5$4Y4Y
'Y
 XY4Y
24Y'Y

If you don't use the {} brackets, the statement immediate following for() will be treated as the
iteration statement. The example below is identical to the one given above:
 X
 Y
54Y
154Y
@@'Y
YYYY *8
9
Y
YYYYYYX !Y Y-%Y3YY
Y
Y6:* %Y
'4Y

I will again recommend you to always use {} brackets and proper indentation.

If you declare a variable in  X''s assignment, its life (scope) will only last inside the loop and
it will die after the loop body terminates (unlike some implementations of C++). ùence if you
write:
 X
 Y
54Y
154Y
@@'Y
6Y
YYYY *8
9
Y
YYYYYYX !Y Y-%Y3YY
Y
Y6:* %Y
'4Y
:Y

@@4YYYYYYYYY77Y
YY

The compiler will complain at line 1 that "i is undeclared identifier".

You can use  and 


 in  or any other loop to change the normal execution path

 terminates the loop and transfers the execution to a point just outside the for loop:

 X
 Y
54Y
154Y
@@'Y
6Y
YYYY
X
2'Y
YYYY6Y
YYYYYYYY 4Y
YYYY:Y
YYYY *8
9
Y
YYYYYYX !Y Y-%Y3YY
Y
Y6:* %Y
'4Y
:Y

The loop will terminate once the value of i gets greater than 5. If some statements are present
after break, break must be enclosed under some condition, otherwise the lines following break
will become unreachable and the compiler will generate a warning (in Java, it's a syntax error).
 X
 Y
5$4Y
14Y
@@'Y
6Y
YYYY 4YYYY77Y, 
%Y *8
9
Y
YYYYYYYYYYYYYY77YX
'4Y
Y   YY
YYYY *8
9
X
'4Y
:Y

   ignores the remaining part of the current iteration and starts the next iteration.

 X
 Y
54Y
154Y
@@'Y
6Y
YYYY
X
55'Y
YYYY6Y
YYYYYYYY
4Y
YYYY:Y
YYYY *8
9
Y
YYYYYYX !Y Y-%Y3YY
Y
Y6:* %Y
'4Y
:Y

Console.WriteLine will be executed for each iteration except when the value of i becomes 5. The
sample output of the above code is:
YYYY!Y Y-%Y3YY
Y
Y*Y
YYYY!Y Y-%Y3YY
Y
Y*Y
YYYY!Y Y-%Y3YY
Y
Y$*Y
YYYY!Y Y-%Y3YY
Y
Y&*Y
YYYY!Y Y-%Y3YY
Y
Y"*Y
YYYY!Y Y-%Y3YY
Y
Y *Y
YYYY!Y Y-%Y3YY
Y
Y*Y
YYYY!Y Y-%Y3YY
Y
Y(*Y
YYYY!Y Y-%Y3YY
Y
Y*Y

" Ñ
The general structure of a do...while loop is
YYYYY
YYYYYYYY   Y Y YY   Y
YYYY,
X Y.- 
'4Y

The statements under  will execute the first time and then the condition is checked. The loop
will continue while the condition remains true. The program for printing the integers 1 to 10 to
the console using the ***,
 loop is:

 Y
54Y
Y
6Y
YYYY *8
9
Y
YYYYYYX !Y Y-%Y3YY
Y
Y6:* %Y
'4Y
YYYY
@@4Y
:Y,
X
15'4Y

Some important points here are:

Y The statements in a ***,


() loop always execute at least once.
Y There is a semicolon ; after the while statement.

" Ñ
The ,
 loop is similar to the ***,
 loop, except that it checks the condition before
entering the first iteration (execution of code inside the body of the loop). The general form of a
while loop is:
YYYY,
XY.- 
'Y
YYYYYYYY   Y Y YY   Y

ur program to u  the integers 1 to 10 to the console using ,


 will be:
YYYY
 Y
54Y
YYYY,
X
15'Y
YYYY6Y
YYYYYYYY *8
9
Y
YYYYYYYYYYX !Y Y-%Y3YY
Y
Y6:* %Y
'4Y
YYYYYYYY
@@4Y
YYYY:Y

 

c
  
n rray is a collection of values of a similar data type. Technically, C# arrays are a reference
type. Each array in C# is an object and is inherited from the System.rray class. rrays are
declared as:
YYYY1 Y -2YJKY1


 2Y5YY
YYYYYY,Y1 Y -2J1
PYY 2K4Y

Lets define an array of type int to hold 10 integers.


YYYY
 YJKY
  Y5Y,Y
 JK4Y

The size of an array is fixed and must be defined before using it. lthough you can use variables
to define the size of array:
YYYY
 Y
PY5Y4Y
YYYY
 YJKY
  Y5Y,Y
 J
PK4Y

You can optionally do declaration and initialization in separate steps:


YYYY
 YJKY
  4Y
YYYY
  Y5Y,Y
 JK4Y

It is also possible to define arrays using the values it will hold by enclosing values in curly
brackets and separating individual values with a comma:
YYYY
 YJKY
  Y5Y6%Y%Y$%Y&%Y:4Y

This will create an array of size 5, whose successive values will be 1, 2, 3, 4 and 5.

 $   


To access the values in an rray, we use the indexing operator [int index]. We do this by passing
an int to indicate which particular index value we wish to access. It's important to note that index
values in C# start from 0. So if an array contains 5 elements, the first element would be at index
0, the second at index 1 and the last (fifth) at index 4. The following lines demonstrate how to
access the 3rd element of an array:
YYYY
 YJKY
 < Y5Y6%Y%Y%Y:4Y
YYYY
 YIY5Y
 < JK4Y

Let's make a program that uses an integral array.


YYYY77Y   Y Y YY  Y
YQY
YYYY 
Y3
Y
X'Y
YYYY6Y
YYYYYYYY77Y
YY



P
Y
YYYYYYYY77YY YY -Y
  Y
YYYYYYYY
 YJKY
  Y5Y6$%Y %Y%Y&%Y":4YY
YYYYYYYY77Y
 
Y  Y Y Y
YYYYYYYY77YY-

Y Y Y
YYYYYYYY X
 Y
54Y
14Y
@@'Y
YYYYYYYY6Y
YYYYYYYYYYYY *8
9
X
  J
K'4Y
YYYYYYYY:Y
YYYY:Y

ùere we used the  loop to iterate through the array and the  *8
9
X' method to
print each individual element of the array. Note how the indexing operator [] is used.

The above program is quite simple and efficient, but we had to hard-code the size of the array in
the  loop. s we mentioned earlier, arrays in C# are reference type and are a sub-class of the
 *<  Class. This class has lot of useful properties and methods that can be applied to
any instance of an array that we define. Properties are very much like the combination of getter
and setter methods in common bject riented languages. Properties are context sensitive,
which means that the compiler can un-ambiguously identify whether it should call the getter or
setter in any given context. We will discuss properties in detail in the coming lessons.
 *<  has a very useful read-only property named Length that can be used to find the
length, or size, of an array programmatically. 0sing the 9 property, the  loop in the
above program can be written as:
YYYY X
 Y
54Y
1
  *9 4Y
@@'Y
YYYY6Y
YYYYYYYY *8
9
X
  J
K'4Y
YYYY:Y

This version of looping is much more flexible and can be applied to an array of any size and of
any data-type.
Now we can understand the usual description of Main(). Main is usually declared as:

Y3
Y
X
YJKY  'Y
The command line arguments that we pass when executing our program are available in our
programs through an array of type
 identified by the   string array.

 
Ñ
There is another type of loop that is very simple and useful to iterate through arrays and
collections. This is the   loop. The basic structure of a foreach loop is:

foreach(<type of elements in collection> <identifier> in <array or collection>) <statements or


block of statements>

Let's now make our previous program to iterate through the array with a foreach loop:
YYYY77Y   Y Y YY  Y
YQY
YYYY 
Y3
Y
X'Y
YYYY6Y
YYYYYYYY77Y
YY



P
Y
YYYYYYYY77YY YY -Y
  Y
YYYYYYYY
 YJKY
  Y5Y6$%Y %Y%Y&%Y":4YY
YYYYYYYY77Y
 
Y  Y Y Y
YYYYYYYY77YY-

Y Y Y
YYYYYYYY  X
 Y
Y
Y
  'Y
YYYYYYYY6Y
YYYYYYYYYYYY *8
9
X
'4Y
YYYYYYYY:Y
YYYY:Y

Simple and more readable, isn't it? In the statement:


YYYY  X
 Y
Y
Y
  'Y

We specified the type of elements in the collection (int in our case). We declared the variable (i)
to be used to hold the individual values of the array 'integers' in each iteration.

#   

Y The variable used to hold the individual elements of array in each iteration (i in the above
example) is readonly. You can't change the elements in the array through it. This means
that   will only allow you to iterate through the array or collection and not to
change the contents of it. If you wish to perform some work on the array to change the
individual elements, you should use a  loop.
Y   can be used to iterate through arrays or collections. By a collection, we mean
any class, struct or interface that implements the !N   interface. (Just go through
this point and re-read it once we complete the lesson describing classes and interfaces)
Y The
 class is also a collection of characters (implements !N   interface
and returns   value in   property). The following code example demonstrates
this and u  all the characters in the string.

YYYY 
Y3
Y
X'Y
YYYY6Y
YYYYYYYY
YY5Y / PY#  4Y
YYYYYYYY  X  Y Y
Y'Y
YYYYYYYY6Y
YYYYYYYYYYYY *8
9
X '4Y
YYYYYYYY:Y
YYYY:Y

This will print each character of the name in a separate line

º $%!

1. ùow were we able to call the Parse method on int? int is a data type and not a class.

2. Write a program that asks a user for 5 numbers and prints the average of these numbers.

3. Write a program that asks for 5 names from the user. Find and print the name which has the
most characters in it.

4. Write a program that processes the following string:



Y  Y5Y 9 
YQY
Y. Y YEY%Y
YYYYYYYYYYYYYYYYYYY -
Y Y;   YR3DYQY
YYYYYYYYYYYYYYYYYYY  YY Y -Y  Y,
 Y-
 Y
YYYYYYYYYYYYYYYYYYYY
YYY  Y
  Y Y
YYYYYYYYYYYYYYYYYYYY Y * 4Y

Iterate through the string and find the number of letters, digits and punctuation characters in it
and u  these to the console.

5. Write a program that prints all the command line arguments.

6. What is the basic difference between int and uint, & and &&, Camel and Pascal Notation,
do...while and while loop, break and continue statement?

$ Ñ#$&!
!
'o
#" (
 !
$  )$ *   
$+   " *(ÑM(,# (-#Ñ(.
The architecture of .Net applications in ×  is designed to look very similar to traditional
Windows applications. When you compile your .Net uu  , the assembly (executable .exe or
library .dll) file is generated. This file contains Win32 header, metadata and manifest and the
MSIL code of modules in the assembly. You execute your application like any other Windows
program by running the exe file. The Win32 header part of the exe invokes the CLR and passes a
pointer to the entry point of your application to CLR. Now, CLR uses the JIT compiler to
compile your code into a native executable as the functions are called. ùence, the .Net parts
(framework, CLR, JITers, MSIL) do exist, but Microsoft has made the whole process transparent
to the u   .

'/"    


"# &*
)
  .#*" )
 
  $o
WriteLine(), Write(), Read() and ReadLine() method of Console class are static, i.e., they belong
to the class and not to the object. So, it's possible to call these functions using the name of the
class without making an object from the class.

+   


   ("
   
 0"


- o.# 


 - (".
If more than one class is available, you will have to specify which class has Main or which
class's Main is to be called using the /main parameter of the command line compiler:
YYYY Y; * Y7
M
 Y

In Visual Studio, right click the project in the solution explorer and select properties. ùere
(Common Properties - eneral - Startup), you can select which class in your program has Main()
or which class's Main is to be used as the entry point of your program.

ÿ#    -   


.
No, it's not possible to have multiple Main() methods in a single class. The compiler will
complain that "Multiple Entry Points Found".

1+   * $ $  $ 


       

Y 4Y
 -Y  - Y
6Y
YYYY Y>
  !- Y
YYYY6Y
YYYYYYYY77Y   Y ,Y Y Y  Y
YYYYYYYY77Y
- Y Y Y YY
YYYYYYYY77Y
-Y YY Y,
,Y
YYYYYYYY 
Y3
Y
X'Y
YYYYYYYY6Y
YYYYYYYYYYYY *8
Y
YYYYYYYYYYYYYYX ; Y  Y YYYYYYYYYMY '4Y
YYYYYYYYYYYY
YY5Y *#9
X'4Y
YYYYYYYYYYYY *8
Y
YYYYYYYYYYYYYYX ; Y  Y Y- Y  MY '4Y
YYYYYYYYYYYY
Y- 5Y *#9
X'4Y
YYYYYYYYYYYY *8
9
X'4Y
YYYYYYYYYYYY *8
9
Y
YYYYYYYYYYYYYYX FMY6:YYYY; MY6: %Y%Y- '4Y
YYYYYYYYYYYY *8
9
Y
YYYYYYYYYYYYYYX FMY6:YYYY; MY6: %Y%Y- '4Y
YYYYYYYYYYYY *8
9
Y
YYYYYYYYYYYYYYX FMY6:YYYY; MY6: %Y%Y- '4Y
YYYYYYYYYYYY *8
9
X'4Y
YYYYYYYYYYYY *8
9
X FYMY6: %Y'4Y
YYYYYYYYYYYY *8
9
X ; MY6: %Y- '4Y
YYYYYYYYYYYY *8
9
X'4Y
YYYYYYYYYYYY *8
9
X FYMY6: %Y'4Y
YYYYYYYYYYYY *8
9
X ; MY6: %Y- '4Y
YYYYYYYYYYYY *8
9
X'4Y
YYYYYYYYYYYY *8
9
X FYMY6: %Y'4Y
YYYYYYYYYYYY *8
9
X ; MY6: %Y- '4Y
YYYYYYYY:Y
YYYY:Y
:Y

 /"
$
  !
$  $ ü $$ üo.
To compile your program select Build - Build Solution or press Ctrl+Shift+B. To execute your
program, select ebug - Start Without ebug or press Ctrl+F5.

+&!
Next time, we will be discussing how to deal with classes in objects in C#:

Y What are classes, objects, member variables (fields), methods, properties?


Y Making a sample class, instantiating and accessing its members
Y efault values
Y ccess Modifiers (private, public, protected, internal, protected internal)
Y Constructors, estructors, Finalize() method
Y Instance members, class members (static)
Y Properties and its significance
Y verloading methods and constructors
Y Value and Reference Types
Y readonly and constants

Anda mungkin juga menyukai