special topics 2 c# summer 2009 luai m. malhis, ph.d 1
TRANSCRIPT
Special Topics 2C#
Summer 2009Luai M. Malhis, PH.D
1
Introduction
The course notes will be taken from many sources on the internet:
Other universities From past courses at An-najah From special sites dedicated to C# The complete set is not available Course notes will be posted on the
OCC
3
Introduction Continue
Course administration: Grading policy: 20% First exam, 20% Second exam, , 20% Assignments ,
40% Final exam.
Text Book: F. Scott Barker Visual C# ® 2005
4
C# Library: .NET Framework Introduced by Microsoft (June 2000)
• Vision for embracing the Internet in software development
Language- and “platform-” independence• Visual Basic .NET, Visual C++ .NET, C# and more• Includes Framework Class Library (FCL) for reuse
Executes programs by Common Language Runtime (CLR)
• Programs compiled to Microsoft Intermediate Language (MSIL)
• MSIL code translated into machine code
(Unlike Java) .NET is mostly Windows (MS) centric• There is a Linux port (e.g., the Mono project)
5
C#: the Language
Developed at Microsoft by Anders Hejlsberg et al.
Based on Java• event-driven, object-oriented, network-aware, visual
programming language
Incorporated into .NET platform• Web based applications can be distributed• Programs that can be accessed by anyone through any
device• Allows communicating with different computer
languages
Integrated Design Environment (IDE)• Makes programming and debugging fast and easy• Rapid Application Development (RAD)
6
It is related to Java and C++– Picking up Java after C# should be easy.
It is simpler than other object-oriented languages [C++]
It is safe and robust --- no core dump or dead console
It has good library and development support – good graphics package– good client-server and network support
It is good for your summer course
However, it is not easy to learn, with many features …
C# Continue
7
C# Translation and Execution
The C# compiler translates C# source code (.cs files) into a special representation called Microsoft Intermediate Language (MSIL)
MSIL is not the machine language for any traditional CPU, but a virtual machine
The Common Language Runtime (CLR) then interprets the MSIL file It uses a just-in-time compiler to translate from
MSIL format to machine code on the fly
8
C# Compilation and Execution
C# sourcecode
MSIL
C#compiler
Machinecode
Just in timecompiler
9
The .NET Framework
Source code MSIL machine language using JIT
Common Language Runtime (CLR): Programs are compiled into machine-specific instructions in two steps:
– First, the program is compiled into Microsoft Intermediate Language (MSIL) which is placed into the application's executable file.
– Using JIT (Just-in-time ) compiler which converts MSIL
to machine language, (JIT compile assemblies into native binary that targets a specific platform )
10
Setting the Path Environment
• Assuming that windows and VS.NET2005 is installed on the C drive on your computer, add the following to the Environment Path:
– C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;– C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin;– C:\Program Files\Microsoft Visual Studio 8\VC\bin;– C:\Program Files\Common Files\MicrosoftShared\VSA\8.0\
VsaEnv;
11
Compiling
The .NET Framework can be thought of as a VM (virtual machine)
• Save any C# program in a text file “example1.cs”, and set the environment variable PATH to point to csc.exe compiler in the .NET framework directory.
– Go to the System Properties by right clicking you My Computer properties Environment variables click on new type pathC:\WINDOWS\Microsoft.NET\Framework\v2.0.50727.
• Now open the command console “cmd” and type “csc example1.cs”.
12
A Simple C# Program
//==========================================================// // // Classes: HelloWorld // -------------------- // This program prints a string called "Hello World!”////==========================================================
using System;
class HelloWorld{ static void Main(string[] args) { Console.WriteLine(“Hello World!”); }}
13
White Space and Comments White Space
Includes spaces, newline characters, tabs, blanklines
C# programs should be formatted to enhance readability, using consistent indentation!
Comments Comments are ignored by the compiler: used
only for human readers (i.e., inline documentation)
Two types of comments• Single-line comments use //… // this comment runs to the end of the line
• Multi-lines comments use /* … */
/* this comment runs to the terminating symbol, even across line breaks */
14
Identifiers
Identifiers are the words that a programmer uses in a program
An identifier can be made up of letters, digits, and the underscore character
They cannot begin with a digit C# is case sensitive, therefore args and Args are
different identifiers Sometimes we choose identifiers
ourselves when writing a program (such as HelloWorld)
Sometimes we are using another programmer's code, so we use the identifiers that they chose (such as WriteLine)
using System;class HelloWorld{ static void Main(string[] args) { Console.WriteLine(“Hello World!”); }}
15
Identifiers: Keywords
Often we use special identifiers called keywords that already have a predefined meaning in the language Example: class
A keyword cannot be used in any other wayC# Keywords
abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach get goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed set short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using value virtual void volatile while
All C# keywords are lowercase!
16
Namespaces Partition the name space to avoid name conflict! All .NET library code are organized using namespaces! By default, C# code is contained in the global
namespace To refer to code within a namespace, must use
qualified name (as in System.Console) or import explicitly (as in using System; )
using System;
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine(“Hello World!”);
}
}
class HelloWorld
{
static void Main(string[] args)
{
System.Console.WriteLine(“Hello World!”);
}
}
17
C# Program Structure
In the C# programming language: A program is made up of one or more classes
A class contains one or more methods
A method contains program statements
These terms will be explored in detail throughout the course
18
C# Program Structure: Class
class HelloWorld
{
}
// comments about the class
class headerclass header
class bodyclass body
Comments can be added almost anywhereComments can be added almost anywhere
19
C# Classes
Each class name is an identifier• Can contain letters, digits, and underscores (_)• Cannot start with digits• Can start with the at symbol (@)
Convention: Class names are capitalized, with each additional English word capitalized as well (e.g., MyFirstProgram )
Class bodies start with a left brace ({) Class bodies end with a right brace (})
20
C# Program Structure: Method
class HelloWorld
{
}
// comments about the class
static void Main (string[] args)
{
}
// comments about the method
Console.Write(“Hello World!”);Console.WriteLine(“This is from CS112!”);
21
C# Method and Statements
Methods– Building blocks of a program– The Main method
• Each console or windows application must have main method defined as static
• All programs start by executing the Main method
– Braces are used to start ({) and end (}) a method
Statements– Every statement must end in a semicolon ;
22
Console Application vs. Window Application
Console Application No visual component Only text input and output Run under Command Prompt or DOS Prompt
Window Application Forms with many different input and output types Contains Graphical User Interfaces (GUI) GUIs make the input and output more user friendly! Message boxes
• Within the System.Windows.Forms namespace• Used to prompt or display information to the user
23
Syntax and Semantics
The syntax rules of a language define how we can put symbols, reserved words, and identifiers together to make a valid program
The semantics of a program statement define what that statement means (its purpose or role in a program)
A program that is syntactically correct is not necessarily logically (semantically) correct
A program will always do what we tell it to do, not what we meant to tell it to do
24
Errors
A program can have three types of errors The compiler will find problems with syntax
and other basic issues (compile-time errors) If compile-time errors exist, an executable
version of the program is not created A problem can occur during program
execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors)
A program may run, but produce incorrect results (logical errors)
25
Constants
A constant is similar to a variable except that it holds one value for its entire existence
The compiler will issue an error if you try to change a constant
In C#, we use the constant modifier to declare a constant
constant int numberOfStudents = 42;
Why constants?– give names to otherwise unclear literal values– facilitate changes to the code– prevent inadvertent errors
26
C# Data Types
There are 15 data types in C# Eight of them represent integers:
– byte, sbyte, short, ushort, int, uint, long,ulong Two of them represent floating point numbers
– float, double One of them represents decimals:
– decimal One of them represents boolean values:
– bool One of them represents characters:
– char One of them represents strings:
– string One of them represents objects:
– object
27
Numeric Data Types The difference between the various numeric types is
their size, and therefore the values they can store:Range
0 - 255-128 - 127
-32,768 - 327670 - 65537
-2,147,483,648 – 2,147,483,6470 – 4,294,967,295
-91018 to 91018
0 – 1.81019
1.010-28; 7.91028 with 28-29 significant digits
1.510-45; 3.41038 with 7 significant digits5.010-324; 1.710308 with 15-16 significant digits
Question: you need a variable to represent world population. Which type do you use?
Type
bytesbyteshortushortintuintlongulong
decimal
floatdouble
Storage
8 bits8 bits16 bits16 bits32 bits32 bits64 bits64 bits
128 bits
32 bits64 bits
28
Examples of Numeric Variablesint x = 1;
short y = 10;
float pi = 3.14;
float f2 = 9.81f;
float f3 = 7E-02; // 0.07
double d1 = 7E-100;
decimal microsoftStockPrice = 28.38m;
29
Boolean
A bool value represents a true or false condition
A boolean can also be used to represent any two states, such as a light bulb being on or off
The reserved words true and false are the only valid values for a boolean type
bool doAgain = true;
30
Characters
A char is a single character from the a character set A character set is an ordered list of characters; each
character is given a unique number C# uses the Unicode character set, a superset of ASCII
– Uses sixteen bits per character, allowing for 65,536 unique characters
– It is an international character set, containing symbols and characters from many languages
– Code chart can be found at:http://www.unicode.org/charts/
Character literals are represented in a program by delimiting with single quotes, e.g.,
'a‘ 'X‘ '7' '$‘ ',‘
char response = ‘Y’;
31
Common Escape Sequences
Escape sequence Description \n Newline. Position the screen cursor to the beginning of the
next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor to the beginning
of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the previous characters output on that line.
\’ Used to print a single quote \\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double quote (") character.
32
string
A string represents a sequence of characters, e.g.,
string message = “Hello World”;
string filepath = “C:\\ProCSharp\\First.cs”;Strings can be created with verbatim string literals by starting with @, e.g.,No escape sequence string a2 = @“\server\fileshare\Hello.cs”;
string filepath = @”C:\ProCSharp\First.cs”;
33
Types
All types are compatible with object-can be assigned to variables of type object
-all operations of type object are applicable to them
34
Value Types versus Reference Types
35
Data Input
Console.Read() Reads a single character from the user input Example char c = Console.Read(); Console.ReadLine()
Used to get a value from the user inputExample string myString = Console.ReadLine();
Convert from string to the correct data type– Int.Parse(), Int16.Parse() Int32.Parse()….
• Used to convert a string argument to an integer• Allows math to be preformed once the string is converted• Example:
string myString = “1023”; int myInt = Int32.Parse( myString );
– Double.Parse(), Single.Parse()
36
Output
Console.Write(exp) prints the exp no end of line close to 20 overlaods Console.WriteLine(exp) prints the exp append end of line close to 20 overloads You can use the values of some variables at some positions
of a string:System.Console.WriteLine(“{0} {1}.”, iAmVar0, iAmVar1);
You can control the output format by using the format specifiers:float price = 2.5f;System.Console.WriteLine(“Price = {0:C}.”, price);
output ------------------ Price = $2.50.
For a complete list of format specifiers, seehttp://msdn.microsoft.com/library/en-us/csref/html/vclrfFormattingNumericResultsTable.asp
Example: TaxAndTotal.cs
Example
// This program gets 10 grades from the user and computes their// average. This is Fig. 4.7 of the textbook.////
==========================================================
using System;class Average1{ static void Main(string[] args) { int total, // sum of grades gradeCounter, // number of grades entered gradeValue, // grade value average; // average of all grades
// initialization phase total = 0; // clear total gradeCounter = 1; // prepare to loop // next slide processing phase
37
Example continue
while (gradeCounter <= 10) // loop 10 times { // prompt for input and read grade from user Console.Write("Enter integer grade: "); // read input and convert to integer gradeValue = Int32.Parse(Console.ReadLine()); // add gradeValue to total total = total + gradeValue; // add 1 to gradeCounter gradeCounter = gradeCounter + 1; } // end of while // termination phase average = total / 10; // integer division // display average of exam grades Console.WriteLine("\nClass average is {0}", average);
} // end of method Main} // end of class
38
39
Arithemtic Operators
Just as in C++/Java Operators can be combined into complex
expressionsresult = total + count / max - offset;
Operators have a well-defined precedence which determines the order in which they are evaluated
Precedence rules– Parenthesis are done first– Division, multiplication and modulus are done second
• Left to right if same precedence (this is called associativity)– Addition and subtraction are done last
• Left to right if same precedence
40
Precedence of Arithmetic Operations
Operator(s) Operation Order of evaluation (precedence) ( ) Parentheses Evaluated first. If the parentheses are nested,
the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, / or % Multiplication Division Modulus
Evaluated second. If there are several such operators, they are evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several such operators, they are evaluated left to right.
Fig. 3.16 Precedence of arithmetic operators.
Code to test arithmetic operations
41
// define variables string firstNumber, secondNumber; int number1, number2; // read two numbers from the input. Console.Write( "Please enter the first integer: " ); firstNumber = Console.ReadLine(); Console.Write( "\nPlease enter the second integer: " ); secondNumber = Console.ReadLine();
// convert numbers from type string to type int number1 = Int32.Parse( firstNumber ); number2 = Int32.Parse( secondNumber );
// do operations int sum = number1 + number2; int diff = number1 - number2; int mul = number1 * number2; int div = number1 / number2; int mod = number1 % number2;
Console.WriteLine( "\n{0} + {1} = {2}.", number1, number2, sum ); Console.WriteLine( "\n{0} - {1} = {2}.", number1, number2, diff ); Console.WriteLine( "\n{0} * {1} = {2}.", number1, number2, mul ); Console.WriteLine( "\n{0} / {2} = {2}.", number1, number2, div ); Console.WriteLine( "\n{0} % {1} = {2}.", number1, number2, mod );
42
Data Conversions
Sometimes it is convenient to convert data from one type to another
– For example, we may want to treat an integer as a floating point value during a computation
Conversions must be handled carefully to avoid losing information
Two types of conversions– Widening conversions are generally safe because
they tend to go from a small data type to a larger one (such as a short to an int)
• Q: how about int to long?– Narrowing conversions can lose information because
they tend to go from a large data type to a smaller one (such as an int to a short)
43
Data Conversions
In C#, data conversions can occur in three ways:– Assignment conversion
• occurs automatically when a value of one type is assigned to a variable of another
• only widening conversions can happen via assignment
• Example: aFloatVar = anIntVar– Arithmetic promotion
• happens automatically when operators in expressions convert their operands
• Example: aFloatVar / anIntVar– Casting
44
Data Conversions: Casting
Casting is the most powerful, and dangerous, technique for conversion
Both widening and narrowing conversions can be accomplished by explicitly casting a value
To cast, the type is put in parentheses in front of the value being converted
For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total:
result = (float) total / count;
Example: DataConversion.cs
45
Compatibility Between Simple Types
46
Assignment Revisited You can consider assignment as another
operator, with a lower precedence than the arithmetic operators
First the expression on the right handFirst the expression on the right handside of the = operator is evaluatedside of the = operator is evaluated
Then the result is stored in theThen the result is stored in thevariable on the left hand sidevariable on the left hand side
answer = sum / 4 + MAX * lowest;
14 3 2
47
Assignment Operators
Assignment operator Sample expression Explanation
+= c += 7 c = c + 7 -= d -= 4 d = d - 4 *= e *= 5 e = e * 5 /= f /= 3 f = f / 3 %= g %= 2 g = g % 2
48
Increment and Decrement Operators
Operator Called Sample expression Explanation
++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides.
++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.
-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.
-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.
Fig. 4.13 The increment and decrement operators.
49
Equality and Relationa Operators
Standard algebraic equality operator or relational operator
C# equality or relational operator
Example of C# condition
Meaning of C# condition
Equality operators == x == y x is equal to y != x != y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to
y <= x <= y x is less than or equal to y Fig. 3.18 Equality and relational operators.
Note the difference between the equality operator (==) and the assignment operator (=)Question: if (grade = 100) Console.WriteLine( “Great!” );
50
More Complex (Compound) Boolean Expressions: Logical Operators Boolean expressions can also use the
following logical and conditional operators:! Logical NOT& Logical AND| Logical OR^ Logical exclusive OR
(XOR) && Conditional AND
|| Conditional OR
They all take boolean operands and produce boolean results
51
Comparison: Logical and Conditional Operators
Logical AND (&) and Logical OR (|)• Always evaluate both conditions
Conditional AND (&&) and Conditional OR (||)• Would not evaluate the second condition if the result of
the first condition would already decide the final outcome.• Ex 1: false && (x++ > 10) --- no need to evaluate the 2nd
condition• Ex 2: if (count != 0 && total /count) {
… }
52
Operations on Enumerations
Console.WriteLine(1 | 4); // bitwise OR 5Console.WriteLine(1 & 4); // bitwise AND 0
Console.WriteLine(true||false); // True
Console.WriteLine(7||1); // Error
Console.WriteLine(6 && 9);// Error
Console.WriteLine(true&& false); // False
Console.WriteLine(!true); // False
53
Operators Associativity Type
() ++ --
left to right right to left
parentheses unary postfix
++ -- + - (type) right to left unary prefix
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
?: right to left conditional
= += -= *= /= %= right to left assignment
Precedence and Associativity
high
low
54
Declaration of Local Variables
55
Additional points on local variables int foo =1; if (foo) { Console.WriteLine("yes"); } ERROR: No implicit conversion between
int and bool
Variables must be assigned before their value is used
int x,y; if (x > 5) y =x;ERROR x must be assigned before used
56
Conditional Statements
A conditional statement lets us choose which statement will be executed next
Conditional statements give us the power to make basic decisions
C#'s conditional statements:– the if statement– the if-else statement – Conitional operator exp1? Va1 : val2; – the switch statement– All just as in c++/Java (close look at conditional operator and
switch)
57
The Conditional Operator
The conditional operator is similar to an if-else statement, except that it is an expression that returns a value
For example: larger = (num1 > num2) ? num1 : num2;
If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger
The conditional operator is ternary, meaning that it requires three operands
58
The Conditional Operator
Another example:
If count ≤ 1, then “Quarter" is stored in result Otherwise, “Quarters" is stored
string result;
int count;
…………
result = (count <=1 ) ? “Quarter” : “Quarters”;
// beginning of the next statement
59
if Statement Example
char ch=‘*’; // char c = Console.Read();int val ;
if('0' <= ch && ch <= '9')val = ch -'0'; else if('A' <= ch && ch <= 'Z')val = 10 + ch -'A';else{val = 0;Console.WriteLine("invalid character {0}", ch);}
60
The switch Statement
The switch statement provides another means to decide which statement to execute next
The switch statement evaluates an expression, then attempts to match the result to one of several possible cases
Each case contains a value and a list of statements
The flow of control transfers to statement list associated with the first value that matches
61
The switch Statement: Syntax
The general syntax of a switch statement is:
switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ...
}
switchswitchandandcasecase
arearereservedreserved
wordswords If If expressionexpressionmatches matches value2value2,,control jumpscontrol jumpsto hereto here
62
The switch Statement
The expression of a switch statement must result in an integral data type, like an integer or character or a string
Note that the implicit boolean condition in a switch statement is equality - it tries to match the expression with a value
63
The switch Statement
A switch statement can have an optional default case as the last case executed in the statement
– The default case has no associated value and simply uses the reserved word default
– If the default case is present, control will transfer to it if no other case value matches
– If there is no default case, and no other value matches the expression, control falls through to the statement after the switch
A break statement is used as the last statement in each case's statement list
– A break statement causes control to transfer to the end of the switch statement
64
switch Statement
Type of switch expressionnumeric, char, enum or string(null ok as a case label).
Type of switch expression: numeric, char, enum or string (null ok as a case label).
65
switch with goto
66
Loops
67
foreach Statement
68
Jumps
{ cc: int z; } int x = 7; if(x<7){ goto cc; }// error no jump into block
Also no jump out of a class
69
Enumerations
List of named constants Declaration (directly in a namespace)
How to use:
enum Color {red, blue, green} // values: 0, 1, 2enum Access {personal=1, group=2, all=4} 1,2,4enum Access1 : byte{ personal=2, group, all} // values 2, 3, 4 •The last definition (Access1) is used to save memory
Color c = Color.blue; // enumeration constants must be qualifiedConsole.WriteLine(c); // writes out blueConsole.WriteLine((int)c); //Writes out 1
70
Operations on Enumerations
Color c = Color. blue;
71
Enumerations, example
enum Season { Spring, Summer, Fall, Winter }; class Example{
public void Method (Season a) { Season b; // local variable} private Season c;
}
Season s = Season.Fall;Console.WriteLine(s); // writes out 'Fall'
string name = s.ToString(); Console.WriteLine(name); // also writes out 'Fall'
Season y = Season.Fall; Console.WriteLine((int) y); // writes out '2'
72
Enumerations, example
using System;
public enum Volume : byte { Low = 1, Medium, High }class EnumBaseAndMembers {public static void Main() { Volume myVolume = Volume.Low; 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(); }}
73
Arrays : One-dimensional Array
int[ ] a = new int[3];
int[ ] b = new int[ ] {3, 4, 5};
int[ ] c = {3, 4, 5};
SomeClass[ ] d = new SomeClass[10];// Array of references
SomeStruct[ ] e = new SomeStruct[10];// Array of values
int len = a.Length; // number of elements in a
74
Multidimensional Arrays
•Rectangular (more compact, more efficient access)int[,] a = new int[2, 3];int x = a[0, 1];int len = a.Length; // 6len = a.GetLength(0); // 2 return the number of rows len = a.GetLength(1); // 3 return the number of columns
•Jagged (like in Java)
nt[][] a = new int[2][];a[0] = new int[3];a[1] = new int[4];int x = a[0][1];int len = a.Length;// 2len = a[0].Length;// 3
int[][] c = new int[ 2 ][ 5 ]; // error
75
Arrays Continue
int[ , ] b = { { 1, 2 }, { 3, 4 } }; int[ , ] b; b = new int[ 3, 4 ];
string [] names={"Bob", "Ted", "Alice"};
76
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;myBools[0][1] = false;myBools[1][0] = true;
Console.WriteLine ("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);
77
myDoubles[0,0] = 3.17;myDoubles[0,1] = 7.157;myDoubles[1,1] = 2.117;myDoubles[1,0] = 556.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]); } }
78
strings
string s1 = "orange"; string s2 = "red";
s1 += s2; System.Console.WriteLine(s1); // outputs "orangered"
s1 = s1.Substring(2, 5); // 2 is start index 5 is length System.Console.WriteLine(s1); // outputs "anger“
int year = 1999; string msg = "ahmad was born in " + year.ToString(); System.Console.WriteLine(msg); // outputs "ahmad was
born in 1999"
79
String 2
string s3 = "Visual C# Express";System.Console.WriteLine(s3.Substring(7, 2)); // outputs "C#"System.Console.WriteLine(s3.Replace("C#", "Basic")); //outputs "Visual
Basic Express“
string s4 = "Hello, World"; char[] arr = s4.ToCharArray(0, s4.Length); // be carefull to range, else
exception foreach (char c in arr) { System.Console.Write(c); // outputs "Hello, World" }
string s6 = "hi to all";System.Console.WriteLine(s6.ToUpper()); // outputs "HI TO ALL" System.Console.WriteLine(s6.ToLower()); // outputs "hi to all"
80
Strings 3
string color1 = "red"; string color2 = "green"; string color3 = "red";
if (color1 = = color3) { System.Console.WriteLine("Equal"); } if (color1 != color2) { System.Console.WriteLine("Not equal"); }
81
Strings 4
When comparing strings, the Unicode value is used, and lower case has a smaller value than upper case.
string s7 = "ABC"; string s8 = "abc";
if (s7.CompareTo(s8) > 0) { System.Console.WriteLine("Greater-than");//Greater-than } else { System.Console.WriteLine("Less-than"); }Will print Greater-than
82
Strings 5To search for a string inside another string, use IndexOf().
IndexOf() returns -1 if the search string is not found; otherwise, it returns the zero-based index of the first location at which it occurs.
string s9 = "Battle of Hastings, 1066"; System.Console.WriteLine(s9.IndexOf("Hastings")); //
outputs 10 System.Console.WriteLine(s9.IndexOf("1967")); //
outputs -1 System.Console.WriteLine(s9.IndexOf('o'); // outputs 79 overloads to ndexof may take strat index length and
others
83
String 6
char[] delimit = new char[] { ' ' }; string s10 = "The cat sat on the mat."; foreach (string substr in s10.Split(delimit) ) { System.Console.WriteLine(substr); }//------------------------------------------------------- //char[] delimit = new char[] { ' ' }; char cf = '*'; string s10 = "The cat sat on the mat."; foreach (string substr in s10.Split(cf)) { System.Console.WriteLine(substr); }
84
Strings 7
string t = "Once,Upon:A/Time\\In\'America"; char[] sep2 = new char[] { ' ', ',', ':', '/', '\\', '\'' }; foreach (string ss in t.Split(sep2)){ Console.WriteLine(ss); }
Program Example
This program keeps reading int from the keyboard until -1 is entered. Prints the sum of all entred numbers. It demonstrate the use of Split and goto
static void Main(string[] args) { int x = -1; int sum = 0; char[] ar = { ' ' }; L1: string inp = Console.ReadLine(); foreach (string s in inp.Split(ar)) { x = int.Parse(s); sum += x; Console.WriteLine(x); } if (x != -1) goto L1; Console.WriteLine("the sum is {0}", sum); }
85
Example 2 Tax Example
static void Main( string[] args ) { // First get amount Console.Write( "Please enter amount: " ); string amountString; amountString = Console.ReadLine(); // get the amount from user
// convert from amount string to floating point number float amount = Single.Parse( amountString );
// Next get tax rate Console.Write( "Please enter tax rate: " ); string taxRateString; taxRateString = Console.ReadLine(); // get the tax rate from user
// convert from string to floating point number float taxRate = Single.Parse( taxRateString );
// Now compute total float total = amount * (1 + taxRate); Console.WriteLine( "Total is {0,5} + {1,5} = {2,5}", amount,taxRate,total );}
86
Constructing output strings
int x = 12 ; double y = 13.4; float z = 12f; char c = 'a'; string s1 = "The sum of " + x + " and " + y + " is " +(x+y);
Console.WriteLine(s1); s1 = "The diff between " + x*2 + " and " + y/2 + " is " + (x*2 -
y/2); Console.WriteLine(s1);
s1 = (x + y).ToString(); ; Console.WriteLine(s1); s1 = 12.ToString(); s1 += 13; Console.WriteLine(s1); s1 = ""; s1 = s1 + z + c;Console.WriteLine(s1); s1 = ""; s1 = s1 + (z + c); Console.WriteLine(s1); s1 = ""; s1 = s1 + z / c; Console.WriteLine(s1);
87
Numeric Formatting
The full syntax for the format string is {N,M:FormatString}, where N is the parameter number, M is the field width and justification, and
FormatString specifies how numeric data should be displayed. Item MeaningC Display the number as currency, using the local currency
symbol and conventions.D Display the number as a decimal integer.E Display the number by using exponential (scientific) notation.F Display the number as a fixed-point value.G Display the number as either fixed point or integer, depending on which format is the most compact.N Display the number with embedded commas.X Display the number by using hexadecimal notation
88
89
Format Specifiers Example1
using System;public class FormatSpecApp {public static void Main(string[] args) {int i = 123456;Console.WriteLine("{0:C}", i); // $123,456.00 currencyConsole.WriteLine("{0:D}", i); // 123456 decimalConsole.WriteLine("{0:E}", i); // 1.234560E+005 exponentialConsole.WriteLine("{0:F}", i); // 123456.00 floatConsole.WriteLine("{0:G}", i); // 123456 generalConsole.WriteLine("{0:N}", i); // 123,456.00 numberConsole.WriteLine("{0:P}", i); // 12,345,600.00 % percentConsole.WriteLine("{0:X}", i); // 1E240 hexadeciaml}}
Format Specifier Example 2
Console.WriteLine("Currency formatting - {0:C} {1:C4}", 88.8,888.8);
Console.WriteLine("Integer formatting - {0:D5}", 88);Console.WriteLine("Exponential formatting - {0:E}", 888.8);Console.WriteLine("Fixed-point formatting - {0:F3}",888.8888);Console.WriteLine("General formatting - {0:G}", 888.8888);Console.WriteLine("Number formatting - {0:N}", 8888888.8);Console.WriteLine("Hexadecimal formatting - {0:X4}", 88);
90
91
Format Specifiers
92
Numeric String Parsing
All the numeric types have a Parse method, which takes the string representation of a number and returns you its equivalent numeric value.
string t = " -1,234,567.890 ";//double g = double.Parse(t); // Same thingdouble g = double.Parse(t, NumberStyles.Any);Console.WriteLine("g = {0:F}", g);
• The NumberStyles is in System.Globalization
93
94
Numeric String Parsing
If you also want to accommodate a currency symbol, you need the third Parse overload, which takes a NumberFormatInfo object as a parameter
using System;using System.Globalization;
public class FormatSpecApp {public static void Main(string[] args) { string u = "£ -1,234,567.890 "; NumberFormatInfo ni = new NumberFormatInfo(); ni.CurrencySymbol = "£"; double h = double.Parse(u, NumberStyles.Any, ni); Console.WriteLine("h = {0:F}", h); // h = -1234567.89
}}
95
Strings and DateTime
A DateTime object stores the date and timeusing System;public class DatesApp{ public static void Main(string[] args){ DateTime dt = DateTime.Now; //now is property Console.WriteLine(dt); Console.WriteLine("date = {0}, time = {1}\n", dt.Date, dt.TimeOfDay); }}
96
Boxing and Unboxing
When you change from value type reference type there is a boxing operation, and when you change from a reference type value type there is an unboxing operation.
Example int f = 42; // Value type. object b= f; // f is boxed to b. int x = (int)b; // Unboxed back to int. Note : Can Unbox only previously boxed value types. Can not unbox reference types
97
Example
using System;
namespace box { enum color{red,green};
struct student { public int id; // must be public in order to accessable public char gender; }
class Program { static void Main(string[] args){ color c = color.green; int f = 42; // Value type. student s; s.id = 11; s.gender = 'f';
Example Continue
object b = f; // f is boxed to b. object cc = c; object dd = s; Console.WriteLine(cc.ToString()); //green cc = b; Console.WriteLine(cc.ToString());//42 int x = (int)b; // Unboxed back to int.
color co = (color)cc; Console.WriteLine(co.ToString()); //42 student ss = (student)dd; //Unboxed back to student Console.WriteLine(ss.id); //11 Console.WriteLine(ss.gender); //'f' } }}
98
99
Boxing and Unboxing
100
Boxing and Unboxing
This Queue can then be used for reference types and value types