the c# language and program structure
DESCRIPTION
The C# Language and Program Structure. Lecture Overview (1). Basics of the C# language for the VB programmer Language syntax The basics of data types Numeric types Integral types Floating point types String types. Lecture Overview (2). Expressions / Parameters / Statements. - PowerPoint PPT PresentationTRANSCRIPT
The C# Language and Program Structure
Slide 2
Lecture Overview (1) Basics of the C# language for the VB
programmer Language syntax The basics of data types
Numeric types Integral types Floating point types
String types
Slide 3
Lecture Overview (2) Expressions / Parameters / Statements
Slide 4
THE BIG DIFFERENCE
C# IS CASE
SENSITIVE
Slide 5
C# Syntax All words are categorized as
Identifiers (programmer chosen names) Keywords (words reserved by the C#
language) You can force a keyword to operate as a
variable using the @ character Literals (numbers or strings you embed
into the application)
Slide 6
C# Syntax Punctuators give structure to the
program The semicolon terminates a statement The { } group statements to form a block
Similar to the Endx in VB Operators (usually a symbol) combine
and transform expressions +, -, *, /
Comments are ignored by the system
Slide 7
Statements In C#, all statements end with a semicolon ;
Statements can span multiple lines There is no need for a continuation character
as in VB Example C#
System.Console.WriteLine( “This is a line of text”);
Example VBSystem.Console.WriteLine( _ “This is a line of text”);
Slide 8
C# Blocks In VB, blocks are marked with keywords
Sub – End Sub If – End If Do Loop While End While
In C#, blocks are all marked with {} as in Java or C++
Slide 9
C# Blocks (Example)namespace Validate{ public static class ValidateNumbers { public static bool IsInteger( string arg) { } }}
Slide 10
Comments XMLSummary comments begin with /// Single line comments are marked
with // Multi-line comments start with /* and
end with */
// A comment.
/* This is Also a comment */
Slide 11
Introduction to Types A type is a blueprint for a value
That blueprint defines the range of allowable values and other information
Types are predefined by the C# language
Custom types you create work the same way
We call this type symmetry
Slide 12
Predefined Types These are types that are supported by
the C# compiler int, string, double, bool, ….
We call these built-in type Not all data types are ‘built-in’
The DateTime data type is part of the .NET Framework class library
Slide 13
Custom Types Complex types are created from
primitive types and other complex types These types contain
Data members Function members
A special function member called a constructuor
Slide 14
Types of Types All types fall into one of the following
two categories Value types comprise most built-in types
enum and struct are also value types Arrays and classes are reference types
Along with just about everything else
Slide 15
Value Types The contents of the variable is simply
the value See figure 2-2 on page 17
Slide 16
Reference Types There are two parts to a reference type
An object A reference to the object
See figure 2-3 on page 18
Slide 17
Null – the Special Case A special case when a reference type
variable DOES NOT point to an object Here is where null reference exceptions
come from
Slide 18
Instance and Static Members
Slide 19
The Type Taxonomy Page 20
Slide 20
Data Types (Selected)C# VB
int Integer
bBool Boolean
Double Double
float Single
date DateTime
string String
object object
See Table 2-1 on page 21
Slide 21
Variable Declarations Variable declarations work the same
way in both C# and VB Local variables are declared inside of a
procedure Module-level variables are declared
outside of a procedure In C#, the declaration syntax is
reversed from VB
Slide 22
Local Variable Declaration (Examples) VB
Dim count As IntegerDim MyName As String = “Ekedahl”
C#int count;string MyName = “Ekedahl”;
Slide 23
Variable Declarations (Examples) VB syntax to declare a module-level
variable Private Counter As Integer
C# syntax to declare the same variable private int Counter;
Slide 24
C# Predefined Type Aliases The .NET Framework defines all types So
System.Int32 I = 5; Is equivalent to
int i=5;
The C# int is just an alias (VB does the same thing)
Slide 25
Introduction to Constructors In an OOP language, objects are created
from their underlying types StreamReader, TextBox, Button…
The new keyword creates a new instance of a custom type
Slide 26
Numeric Type Conversion C# implicitly allows “widening type
coercion” More restrictive types are implicitly
converted to less restrictive types The reverse conversion MUST be expicit
Slide 27
Operators (Arithmetic) Mathematical operators are the same
(+, -, #, /) for both VB and C# with a few exceptions % is the modulus operator (Mod) ++ and -- are post and pre-increment and
decrement operators
Increment count (Example)count++;
Slide 28
Specialized Integral Operations When operands are both integers, any
remainder is truncated Exceptions are not thrown for underflow
or overflow Beware of short and byte
Slide 29
Specialized Floating-point Operations +- infinity has a special value Not a
Number (NaN) Division by 0
Slide 30
The Decimal Data Type Use for man-made values such as
currency 28-29 significant digits of precision
Slide 31
The Boolean Data Type bool is equivalent (aliased) to
System.Boolean It stores the literal value true or false The runtime stores the value in one byte
Use the BitArray class for more efficient storage
Don’t convert from numeric to boolean data types!
Slide 32
Operators (Logical) (Boolean) They are pretty much the same from VB
and C# Inequality (<>) in VB is (!=) in C# Equality (=) in VB is (==) in C#
In C#, the single (=) is always used for assignment statements
Use caution with floating point values and rounding error
Slide 33
Logical Operators and Value / Reference Types The notion of equality is obvious for
numeric types Reference types work differently
Equality is based on reference, rather than content
Reference types are equal if two variables point to (reference) the same object
Slide 34
Conditional Operators These are quite different but do the
same thing
VB C#
And &
AndAlso &&
Or |
OrElse ||
Xor ^
Not !
Slide 35
Conditional Operators (Short Circuiting) They are used to test for a null
reference that would otherwise throw an exception if used
The improve efficiency
Slide 36
Decision-Making Statements (if) if statements take a boolean
expression as an argument Note the parentheses are required
if (i >= 0){ // do something if i is // greater than 0}
Slide 37
Decision-Making Statements ( 2-way if) Use the else keyword to create a 2-way if statement
if ( i >= 0){ // Do something if i is // greater than 0.}else{ // Do something else.}
Slide 38
Decision-Making Statements ( multi-way if) Use else if to create multi-way decisions if (i > 0){ // Do something if i is // greater than 0.}else if (i < 0){ // Do something else.}else{
// i must be equal to 0.}
Slide 39
Decision-Making Statements (switch) C# uses the switch statement instead
of Select Case Both work the same way The break keyword must appear at the
end of each case
Slide 40
switch statement (Example)
switch (day){
case 0:DayOfWeek = “Sunday”;break;
case 1:DayOfWeek = “Monday”;break;
}
Slide 41
Strings (VB Comparison) Definition - An immutable sequence of
Unicode characters Use the System.String data type as in
VB; The C# string type maps to System.String
The string concatenation operator is + instead of &
The members are the same between C# and VB
Slide 42
The char Data Type It’s a single Unicode character Use the backslash “\” character to
‘escape’ special characters
Store the letter ‘a’ in the char variable cchar c= ‘a’;
Store the backslash character in the variable bschar bs = ‘\\’;
Slide 43
The char Data Type (Escape sequences
Slide 44
Using the char Data Type Every char has a unique UNICODE value We can get this value and test character
codes We can insert characters not on your
keyboard
Slide 45
The string Data Type It’s an alias for System.String Literal values appear inside double
quotes Even though strings are reference
types, the test for equality tests the string value rather than the string reference The <> are not supported. Use the CompareTo method
To create a verbatim string literal preface the literal with the @ character
Slide 46
Variables and Parameters Remember that a variable is just a
storage location. And a variable contains a modifiable value
Variables can be categorized as: Local variables (declared in a procedure
or block) Parameters passed to procedures
(arguments) Instance or static fields (roughly public
and private variables) Array elements
Slide 47
Slide 48
Memory Allocation of Variables Logically, memory is allocated from two
places The stack (stores local variables and
parameters) It’s also how we return from a procedure
The heap stores reference type instances The CLR periodically cleans the heap
Slide 49
Procedures and Parameters Visual Basic has Function and Sub
procedures C# works a bit differently
Procedures that don’t return a value have a data type of void
Procedures that do return a value have an explicitly defined data type
Slide 50
Procedures (Example 1) The following procedure does not return
a value
private void InitializeLocal(){ // Statements}
Slide 51
Procedure Parameters (By Value and by Reference) Conceptually the same as VB
By value – A copy of the parameter is passed to the procedure – The procedure operates only on the copy
By reference – a reference to the object is passed to the procedure – The procedure operates on the reference thus the actual value
Slide 52
Procedure Parameters (By Value and by Reference) By default, C# variables are passed by
value Use the ref modifier to pass an
argument by reference Use the out modifier to pass an
argument by reference Works like ref but the value is assigned
somewhere in the function
Slide 53
Optional Parameters
Slide 54
Procedures (Example 2) The following procedure returns a value
having a data type of bool (Boolean)
public static bool IsInteger(string arg, out int result)
{ if (System.Int32.TryParse(arg, out result) == true) { return true; } return false;}
Slide 55
Calling Procedures To call a procedure, use it’s name If the argument list is empty, the () are
required
Call the procedure foo without arguments
foo();
Slide 56
Expressions and Operators An expression denotes a value (In its
simplest form, a constant expression) 13
An expression contains operators and operands 13 * 10
See table 2-3 on page 46
Slide 57
Statements Two types
Declaration statements create (declare) variables
Expression (executable) statements Change the state of something, such as an
assignment statement or a method call
Slide 58
Loops (Introduction) while is used to create a pre-test loop
(Do While) do is used to create a post-test loop (Do Until)
for loops are used when the iteration count is known in advance
Slide 59
while Loops While loops take a boolean expression
enclosed in parenthesis The loop executes while the condition is
true {} mark the while block instead of End While
Slide 60
while Loops (Example)int i;while (i < 10){
System.Console.WriteLine(i);i++;
}
Slide 61
do Loops Do loops test the condition after the
loop has executed once Example:do { System.Console.WriteLine(x); x++; // Post increment operator} while (x < 5);
Slide 62
for Loops Like VB, for loops can be used when
the number of loop iterations is known in advance The syntax is quite different though
Slide 63
for Loops (Syntax)for ( init-expr; cond-expr; loop-expr ){ // statement block} int-expr contains the expression’s
initial value cond-expr contains the condition loop-expr updates the expression
Slide 64
for Loops (Example) Print the counting numbers from 1 to 10
for (int i = 0; i < 10; i++){
System.Console.WriteLine(i);}
Slide 65
foreach loops foreach loops are used to enumerate
arrays and collections We will talk about collections more later
When using a foreach loop you need not explicitly increment or decrement the counter
We will talk much more about these later in the course
Slide 66
foreach loops (Example) Declare and enumerate a one-
dimensional array named fibarray
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray){ System.Console.WriteLine(i);}
Slide 67
Exiting a Loop Prematurely Use the break statement to exit a loop Use the continue statement to jump to
the loop’s condition The condition is tested immediately
There is a goto statement to jump to a named label but we will NEVER use it
Slide 68
THE FOLLOWING MATERIAL IS NOT IN THE BOOK CHAPTER
Slide 69
Type Conversion (Introduction) In IS 350, you used val to convert
strings to numbers In C#, val is used to declare implicitly
typed variables We will use a much different strategy
here Each primary data type supports a
method named TryParse The method accepts 2 arguments
The string to parse The output result
Slide 70
TryParse (Example) Try to parse the string arg and store the
result in outstring arg = "123";double result;if (System.Double.TryParse(arg, out result) == true)
{ return true;}return false;
Slide 71
Using System.Convert Members of System.Convert class also
convert one type to another System.Convert.ToInt32 System.Convert.ToDouble System.Convert.ToDateTime …
Slide 72
Constants Constants are just variables whose
value does not ever change Declare with the const statement Constants can only be initialized when
they are declared
Slide 73
Constants (Example) Declare and initialize constants
const int x = 0;public const double gravitationalConstant = 6.673e-11;
private const string productName = "Visual C#";
Slide 74
Null VBs Nothing keyword is null in C# VBs Me keyword is this in C#
Slide 75
Events (Introduction) In IS 350, you used events (event
handlers) without really knowing how they work
In VB, all events are Sub procedures because they do not return a value
In C#, they are of type void
Slide 76
Events (Introduction) Events always have two arguments The first, named sender, contains a
reference to the object that fired the event
The second, named e, contains the event data It has a data type of System.EventArgs or
a class that derives from System.EventArgs
Slide 77
Event Wiring – (Introduction) Ever wonder how an event handler
executes? In VB, it’s the Handles clause In C#, it’s a bit more primitive
You create an instance of the event handler and assign it to the event name
This is what we call a delegate
Slide 78
Wiring an Event (VB) The following procedure handles the Click event for the button named btnCalculate
ExamplePrivate Sub btnCalculate_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnCalculate.Click
Slide 79
Wiring an Event (C#) Every control has properties that
correspond to events (Click for example)
The event procedure is named btnExit_Click in this example
this.btnExit.Click += new System.EventHandler( this.btnExit_Click);
Slide 80
Event (Example) MouseMove fires when ever the mouse
is movedprivate void frmMain_MouseMove(object sender, MouseEventArgs e) {
this.Text = "Position x=" + e.X.ToString() + " y=" + e.Y.ToString(); }