chapter 3 c# basics

33
Chapter 3 C# Basics This chapter discusses the following topics: Identifiers, variables and constants Declaring variables and constants Data types Operators and expressions Assignment statements Input/Output statements Namespaces. 3.1 Identifiers Identifiers are names used to represent variables, labels, object names, named constants and functions (methods). An identifier can be 1 to 255 characters long (although it seldom exceeds 30 characters) and it is formed by combining upper and/or lower case letters (A to Z, a to z,), digits (0 to 9) and the underscore (_). Special characters such as @, #, *, ?, period (.) and blank (white space) are not allowed in an identifier. An identifier must start with a letter and may be followed by one or more letters, digits or underscores. Keywords (or reserved words) are predefined reserved identifiers that have special meanings to the compiler.

Upload: amexs-jonny-laivoi

Post on 13-Sep-2015

22 views

Category:

Documents


3 download

DESCRIPTION

This chapter discusses the following topics:• Identifiers, variables and constants• Declaring variables and constants• Data types• Operators and expressions• Assignment statements• Input/Output statements• Namespaces.

TRANSCRIPT

Chapter 1

3-4 ( Chapter 3

C# Basicsl_ ( 3_-3

Chapter 3

C# Basics

This chapter discusses the following topics:

Identifiers, variables and constants

Declaring variables and constants

Data types

Operators and expressions

Assignment statements

Input/Output statements

Namespaces.

3.1 Identifiers

Identifiers are names used to represent variables, labels, object names, named constants and functions (methods). An identifier can be 1 to 255 characters long (although it seldom exceeds 30 characters) and it is formed by combining upper and/or lower case letters (A to Z, a to z,), digits (0 to 9) and the underscore (_). Special characters such as @, #, *, ?, period (.) and blank (white space) are not allowed in an identifier. An identifier must start with a letter and may be followed by one or more letters, digits or underscores.

Keywords (or reserved words) are predefined reserved identifiers that have special meanings to the compiler. Keywords cannot be used as identifiers in a program. That means you should not use words such as Console, For, Switch, WriteLine and While as identifiers.

The list of keywords in C# is given below.

abstracteventnewstruct

asexplicitnullswitch

baseexternobjectthis

boolfalseoperatorthrow

breakfinallyouttrue

bytefixedoverridetry

casefloatparamstypeof

catchforprivateuint

charforeachprotectedulong

checkedgotopublicunchecked

classifreadonlyunsafe

constimplicitrefushort

continueinreturnusing

decimalintsbytevirtual

defaultinterfacesealedvolatile

delegateinternalshortvoid

doissizeofwhile

doublelockstackalloc

elselongstatic

enumnamespacestring

C# is case sensitive, meaning, it distinguishes between upper and lowercase letters. That means, it will treat the variables Total, total and totaL to mean three different variables. (Variables are identifiers used to store data items held in memory locations.)

Here are some examples of correctly formed identifiers:

Correct Identifiers

Total

AccountBalance

Interest_rate

Rate_of_return

Root1

The following are some examples of incorrectly formed identifiers:Incorrect Identifiers

Reason

Date?Contains ?

Interest rateContains blank

Amount$ PayableContains $ and blank

123Starts with a number

e.oneContains .

@fsktm.um.edu.myContains @ and .

http://www.wcg.orgContains :, / and .

When forming identifiers, the following naming convention is helpful:

1. Use meaningful (sensible) names. For example, you should use a variable name such as Total or Sum to store the total of a set of values instead of a variable name s or q9zxc.

2. If a variable is long (containing more than one word), use mixed cases or underscores to connect the words in the variable. For example, you can use the names TotalPay, Total_Pay or total_pay to store the total pay of all the employees in a company (C# will treat these as different variables).

3. Prefix each identifier with a lowercase prefix to specify its data type (data types are discussed later in the chapter). For example, you can declare the variable dblTotal instead of the variable Total of type double.

4. Capitalize the first letter of the word following the prefix.

3.2 Variables & Constants

Variables are identifiers used to reference data items stored in memory locations in the computer. Each memory location can hold a piece of data item such as a number or a character. The values stored in these locations can be changed during program execution.

Constant variables are similar to variables, but their values cannot be changed during program execution. For example, in a program that computes areas of circles, radius will be a variable while pi (the value 3.142) will be a constant variable. To declare a constant variable, you must prefix the keyword const before the data type.

Literals are fixed or constant values assigned to variables. They can be numeric, characters, strings, Boolean or other data types.

The following are some examples of variables, constants and literals:

Commission

ROI

GrossPay

Interest_Rate

Sum_of_x

Epsilon

Sumx2

acts of chivalry // this is a string literal

1234567

// this is also a numeric literal

*

// this is character literal

false

// this is a Boolean literal

There are also literals which have specific meaning. They are called escape sequences or escape characters. These are useful for input/output whether on the console or printer. The table below gives the list of these escape sequences.

Escape

sequenceCharacter

produced

Meaning

\aAlert/beepBeep the computer speaker

\bBackspaceMove to one position to the left

\fForm feedMove to the next page

\nNew lineMove to the next line

\rCarriage returnMove to the beginning of the current line

\tHorizontal tabMove to one tab position

\vVertical tabMove a fixed number of lines down

\Single quotePrint a single quote

\Double quotePrint a double quote

\\BackslashPrint a backslash

Here are some examples:

// Print Hello world! on the next line

Console.WriteLine(\nHello world!);

// Print Hello world! on the next tab position

Console.WriteLine(\tHello world!);

// Print Hello world! on the next page

Console.WriteLine(\fHello world!);

// Print Hi and beep

Console.WriteLine(\aHi);

// Print the character \

Console.WriteLine(\\);

3.3 Declaring Variables & Constants

Before you can use a variable in a program, you must declare it in a declaration statement. The declaration will include the name of the variable and its data type such as int (integer), double, and string. (Data types are discussed below.) C# will use this information to allocate sufficient memory for the variable. Some data types require more memory than others. For example, a variable of type double will require 8 bytes while a variable of type int will require only 4 bytes.

Variable declaration takes the general form

where type refers to data type and var1 to varn are the names of variables separated by a comma. The semicolon terminates the statement.

The following are some examples of variable declaration:

string ProductCode;

int Quantity;

double Price;

decimal Amount;

float rate;

char ch;

int x, y, z; // you can declare more than 1 variable

// of the same data type in the same line

You can also assign initial values to variables in a declaration statement as in the following statements:

char ch = a;

int n = 20;

double total = 0.00;

Constants have fixed values, i.e., their values dont change during the course of program execution. A constant is declared by using the keyword const followed by the type and name of the constant (an identifier), the assignment operator and the constant value. It takes the general form:

The following are some examples of constant declaration:

const double Rate = 7.50;

const decimal TotalPay = 99999999.99;

const int BufferSize = 1024;

const string Greetings = Hello there;

const string WebSite = http://www.must.edu.my;

To distinguish between the different data types, programmers often use certain conventions for naming variables and constants. They prefix each variable or constant with 3 lowercase letters representing the data type. The table below shows the prefixes for several data types.

Data TypePrefixData TypePrefix

boolblndecimaldec

bytebteint int

shortshrlonglng

floatfltstringstr

doubledblchar chr

The following are some examples of variable and constant declarations using the above convention:

string strProductCode;

int intQuantity;

const double dblRate = 7.50;

3.4 Data TypesWhen you declare a variable or a constant, you must specify its type. The data type tells what type of data (Boolean, integer, double, string, etc) will be stored in the computers memory. C# uses this information to allocate the correct amount of memory to store the variable or constant.

C# supports several data types such as Boolean, byte, integer, long, float, double, character and string. The table below shows the various data types, their ranges and the amount of memory (in bytes) needed to store them.

Data TypeAlias ForAllowed Values

sbyteSystem.SByte-128 to 127

byteSystem.Byte0 to 255

shortSystem.Int16-32,768 to 32,767

ushortSystem.UInt160 to 65,535

intSystem.Int32-2,147,483,648 to 2,147,483,647

uintSystem.UInt320 to 4,294,967,295

longSystem.Int64-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

ulongSystem.UInt640 to 18,446,744,073,709,551,615

floatSystem.Float1.5(10-45 to 3.4(1038

doubleSystem.Double5.0(10-324 to 1.7(10308

decimalSystem.Decimal1.0(10-28 to 7.9(1028

charSystem.Char0 to 65535

boolSystem.BooleanTrue or false

stringSystem.StringA sequence of characters

You must choose the appropriate data type for the variables you use. For example, you can choose the short data type for small integer numbers (positive and negative), int for bigger integer numbers, and long for very large integer numbers. If you only need positive integers (for example, to store the population of a country), then you can use the unsigned integer data type uint. For calculations involving financial calculations, you can choose the decimal data type. Similarly, for single characters, you would choose the char data type, and for a string of characters, you would choose the string data type.

3.5 Operators & Expressions

Operators trigger some computation when applied to operands in an expression. There areseveral categories of operators such as arithmetic, relational, logical, and assignment operators.

Arithmetic Operators

The arithmetic operators are as follows.

OperatorAction

-Subtraction (also unary minus)

+Addition

*Multiplication

/Division

%Remainder (modulus)

>>Shift bits right

b && c > dwill yield falseOther Operators

C# has other operators such as the following:

OperatorMeaning

isTests data/object type

?:Simple ifelse

thisRefers to current object

The is operator tests the data type of a variable. The ?: operator is a simple ifelse conditional operator. The this operator references the current object.

Example

If i is of type int (integer) and x is of type double,

i is double will yield the value falsex is double will yield the value trueExample

If sex is of type char and status is of type string, the statement

status = (sex == M ? Mr : Ms);

will assign the string Mr to status if sex is equal to M, otherwise it will assign Ms.

Example

If small, x and y are of type int, the statement

small = (x Save as c:\messagebox.cs.

3. Go to Start and select

Programs > Microsoft Visual Studio 2005 > Visual Studio Tools > Visual Studio 2005 Command Prompt

4. Change to c drive, then compile and run as shown in the screen below.

The output will appear in a message box.

3.10 Namespaces

A namespace is a collection of related classes. It provides unique identifiers for types by placing them in a hierarchical structure. It also provides help in avoiding name clashes between two sets of code. The classes of the System namespace are given below.

The fundamental programming namespaces in the .NET Framework include:

NamespaceClasses Contained

SystemMost fundamental classes that are frequently used. For example the class object, from which every other class is derived, is defined in System, as are the primitive data types int, string, double etc.

System.ReflectionClasses that allow examination of the metadata that describes assemblies, objects and types. Also used for COM Interoperability.

System.IOInput and output, file handling, etc.

System.CollectionsArrays, lists, linked lists, maps and other data structures.

System.WebClasses that assist in the generation of web pages using ASP+.

System.NetClasses to make requests over the network and Internet

System.DataADO+ classes that make it easy to access data from relational databases and other data sources.

System.WinFormsClasses to display controls for standalone

windows applications (as opposed to web).

Microsoft.Win32Functions which were previously accessible mainly through the Win32 API functions, such as registry access.

The classes in the System namespace are shown below.

Example

Program 3.8 shows how to create a namespace. To declare a new namespace csharp, you put the reserved word namespace in front of csharp. Curly braces surround the members inside the csharp namespace.

Program 3.8

using System;

namespace csharp//Namespace declaration

{

class NameSpaceCSS

{

public static void Main()

{

//Write to console

Console.WriteLine("csharp namespace");

}

}

}

Example

Program 3.9 shows how to create a nested namespace. By placing the code in different sub namespaces, we can keep our code organized.

Program 3.9

using System;

namespace csharp//Namespace declaration

{

namespace csharp2 //Namespace declaration

{

class NameSpaceCSS //Program start class

{

public static void Main()

{

//Write to console

Console.WriteLine("nested namespaces");

}

}

}

}

Exercise

3.1List the main data types provided in C#.

3.2 Writeappropriate declarations, assigning initial values(if any), for each of the following:

(a) Integer variable: index

Unsigned integer variable: cust_num

Double-precision variables: gross, tax, net

(b) String variables: first, last

80-element string: message

String variable: prompt = ERROR

(c) Floating-point variables: root1 = 0.007, root2 = -6.8

Integer variable: big = 781111222

Double variable: Amount = 999999999.99

3.3Given integer variables x, y and z with values 10, 7, 2 respectively,

determinethe value of each of the following arithmetic expressions:

(a) x+2*y-z

(b) x/z-(x*x+y)

(c) (x*y)%z

(d) 5*(x+y+z)-x/z

(e) x*y-x*z

(f) y*(x+z)*(x-y)

3.4Given integer variables a = 2, b = 5, c = 7 and floating-point variables x = 10.0, y = 10.5, z = 20.0. Use type casting toobtain accurate answers for each of the following expressions:

(a) y+a/b

(b) a+b*(z/a)

(c) x+(b/a)*c

3.5. Using the values given in question 3.4, determine thevalues for the each of the expressions given below:

(a) a++

(b) a5.0

(c) c>=a

(d) ac(e) z!=10.0(f) a==253.6Given the following declarations and initial assignments:int i=4, j=21, k;float x=94.55, y;char a='z', b='t', c=' ';Determine the value of each of the following assignments:(a) k=i*j;(b) y=x+i;(c) y=k=j;(d) a=b=c;(e) i+=j;(f) j-=(k=5);3.7Explore the classes in the System namespace and determine their purpose.3.8What is the purpose of boxing and unboxing a variable/object? Illustrate with a simple example.3.9What is the purpose of checked and unchecked? Illustrate with a simple example.3.10Why do you need two types of data structures (stack and heap) for storing variables and references to instance variables?3.11 What is the purpose of garbage collector? What will happen if there is no garbage collector?NetGlobalizationDiagnosticsConfigurationCollectionsx is boxed5intxyobject y = x;int x = 5;System HYPERLINK "ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfsystemthreadingthreadexceptioneventhandlerclasstopic.htm" ThreadExceptionEventHandlerThreadStateThreadStartTimeoutTimerThreadPoolThreadStringBuilderASCIIEncodingEncodingEncoderDecoderStringWriterStringReaderStreamWriterStreamReaderIOExceptionFileStreamFileDirectoryIComparerIListICollectionQueueStackSortedListBitArrayArrayListThreadingTextSecurityRuntime5On the heapOn the stackResourcesReflectionvariable = expression;IOconst type var = value;type var1, var2, , varn;