You are on page 1of 57

C#

C#s Family Tree


C# inherits a rich
programming legacy
from C (1972) and
C++ (1979).
It is closely related
to Java (1991).

A Faster Start
C# does NOT require the use of pointers,
object destructors, and the use of #include
Command prompt or Visual Studio IDE
No String[] args needed in main method
header as in Java (optional)
Class name does not have to match file name
Can use .exe name to execute in the
command line interface
File can contain multiple classes
3

Object Oriented Language


Methods and variables in object-oriented
programming are encapsulated, that is, users are
only required to understand the interface and not the
internal workings of the class
Polymorphism and Inheritance are two
distinguishing features in the object-oriented
programming approach
Polymorphism describes the ability to create methods
that act appropriately depending the context
Inheritance provides the ability to extend a class so
as to create a more specific class

Similarities and Differences


from C++ and Java
Functions are called Methods
main() becomes Main()
Namespace - class - object - method
relationship introduced early
Save files with .cs extension
writeln() becomes WriteLine()
Hello.cs
Hello2.cs
5

Writing a C# Program that Produces


Output

This is my first C# program is a literal string of characters


The string appears in parenthesis because it is a parameter
or an argument
The WriteLine() method prints a line of output on the screen

Writing a C# Program that Produces


Output

Out is an object that represents the screen


The Out object was created and endowed
with the method WriteLine()
Not all objects have the WriteLine() method
7

Writing a C# Program that Produces


Output

Console is a class
Console defines the attributes of a collection of
similar Console objects
8

Writing a C# Program that Produces


Output

System is a namespace, which is a scheme


that provides a way to group similar classes
Namespaces are used to organize classes
9

Compiling and Executing a Program


from the Command Line
After creating source code, you must
do the following before you can view
the program output:
Compile the source code into
intermediate language (IL)
Use the C# just in time (JIT) compiler to
translate the intermediate code into
executable statements
10

Selecting Identifiers

Every method used in C# must be part of a


class
A C# class name or identifier must meet the
basic following requirements:
An identifier must begin with an underscore or a
letter
An identifier can contain only letters or digits, not
special characters #,$, or &
An identifier cannot be a C# reserved keyword

11

Variables
All variables are objects
As objects, all types have built-in methods
Creating formatted output is easy
Variables.cs
Characters are not one byte, they are two
bytes due to Unicode (0 to 65535)
Global Portability

12

Data Types
byte

1 byte

Range
0 to 255

Unsigned
byte

sbyte

1 byte

Range
-128 to 127

Signed
byte

short

2 bytes

Range
Signed
-32768 to 32767 short

ushort 2 bytes

Range
0 to 65535

Unsigned
short
13

More Integer Data Types


int

4 bytes

Range
-2,147,483,647 to
2,147,483,647

uint

4 bytes

Range
0 to 4,294,967,295

Signed
integer
Unsigned
integer

long

8 bytes

Greater than
900,000 trillion

Signed
long int

ulong

8 bytes

Greater than 18
million trillion

Unsigned
long int
14

float

Other Data Types

4 bytes Range

A number 38 zeros long

double

8
bytes

Range

decimal 8
bytes

Range

string
char

Range N/A
Range

bool

N/A
2
bytes

A number 308 zeros long

A number 28 zeros long

Float
number
Double
precision
Fixed
precision
Unicode

0x0000 to 0xFFFF

Unicode
character

True or False

Boolean
15

Using the String Type


The Equals Method returns True or False
The Compares Method returns a zero if two
words are the same, a positive number if
the first word is greater than the second,
and a negative number if the first word is
less than the second.
Strings.cs
16

New Data Types


byte = 1 byte Range = 0 to 255
sbyte = 1 byte Range = -128 to 128
Decimal for monetary calculations
Range 1E - 28 to 7.9E + 28

Decimal.cs
C++ often was subject to a variety of rounding
errors. The decimal data type can accurately
represent up to 28 decimal points.
17

Formatting Output
Format
Character

Description

Default Format (if no


precision is given)

C or c

Currency

($##,###.##)

D or d

Decimal

[-]########

E or e

Scientific
(exponential)

[-]#.#######E+###
[-]#.######e+###

F or f

Fixed Point

[-]########.##
18

Example of Formatting
Console.WriteLine(Floating Amount:
{0,0:$###.##}, 3.14);
Prints: Floating Amount: $3.14
Console.WriteLine(Floating Zeros:
{0,0:$000.00}, 3.14);
Prints: Floating Amount: $003.14
19

Formatting Output Cont.


Format
Character

Description

Default Format (if no precision is


given)

G or g

General

Either general or scientific

N or n

Number

[-]##,###.##

P or p

Percent

Represents a passed numeric value


as a %

R or r

Round trip

Ensures that numbers converted to


strings will have the same value
when they are converted back into
numbers

X or x

Hexadecimal

Minimum hexadecimal (base 16)

20

Examples of Formatting
double someMoney = 123;
string moneyString;
moneyString = someMoney.ToString("F");
Console.WriteLine(moneyString);
moneyString = someMoney.ToString("F3");
Console.WriteLine(moneyString);
Console.WriteLine(someMoney.toString("C2")
The first WriteLine() statement in the following
code produces 123.00, the second produces
123.000, and the third produce $123.00.
21

Using the string Data Type to


Accept Console Input
You can use the Console.ReadLine()
method to accept user input from the
keyboard.
This method accepts all the characters a user
enters until the user presses Enter. The
characters can be assigned to a string.
For example, the statement:
myString = Console.ReadLine(); accepts a
users input and stores it in the variable
myString.
22

Boolean Variables
Values are true/false (no 1/0 like C++)
If statements must use == for
equivalency
If you fail to use ==, it will not compile
Attempting to use an uninitialized variable

If.cs
23

Relational Operators

24

Escape Sequences

25

Time for You to Try!


Temperature Conversion Program
Allow the User to Input a Fahrenheit
temperature and convert it to Celsius
Result should go out 2 decimal places
Formula = (F - 32) x (5/9)
Test Data = 90 F is 32 C
26

If Statement
Like C++ and Java
IfElseDecision.cs
IfElseDecisionWithInput.cs
Comments can be written 3 ways
/* The old C way Block Comments */
// The C++ way Line Comments
/// The XML way
27

Operator

Logical
Operators
Meaning Effect

&&

AND

Connects two expressions into one. Both


expressions must be true for the overall
expression to be true.

||

OR

Connects two expressions into one. One or


both expressions must be true for the overall
expression to be true. It is only necessary for
one to be true, and it does not matter which.

NOT

The ! operator reverses the truth of an


expression. It makes a true expression false,
and a false expression true.
28
28

Making Decisions Using the switch


Statement
The switch structure uses four new keywords:
switch starts the structure and is followed immediately
by a test expression
case is followed by one of the possible values that
might equal the switch expression
break optionally terminates a switch structure at the
end of each case
default optionally is used prior to any action that
should occur if the test expression does not match any
case

29

Switch Statement
No fall-through rule
Switch.cs

30

Loops
While Loop
Do While Loop
For Loop
A loop is a structure that allows
repeated execution of a block of
statements
31

Using the while Loop


You can use a while loop to execute a body of
statements continuously while some condition
continues to be true
A while loop consists of the keyword while, followed
by a Boolean expression within parentheses, followed
by the body of the loop
A loop that never ends is called an infinite loop

32

Using the while Loop


To make a while loop end, three separate actions should
occur:
Some variable, the loop control variable, is initialized
The loop control variable is tested in the while
statement
The body of the while statement must take some action
that alters the value of the loop control variable

33

Using the for Loop


A loop that executes a specific
number of times is a definite
loop or a counter loop
When you use a for statement,
you can indicate the starting
value for the loop control
variable, the test condition that
controls loop entry, and the
expression that alters the loop
control variable
34

Using the for Loop


The three semicolon separated sections
of a for statement are used for:
Initializing the loop control variable
Testing the loop control variable
Updating the loop control variable

35

Using the for Loop

Printing integers 1 through 10 with while and for loops

36

Methods
All methods must have an explicit return type
No int default when returning variables
Methods can have four types of arguments:
Value
ParameterDemo1.cs
Reference
ParameterDemo2.cs
Output
ParameterDemo3.cs
Params
ParameterDemo4.cs
37

Overloading Methods
Overloading involves using one term to
indicate diverse meanings
When you overload a C# method, you
write multiple methods with a shared name
The compiler understands the meaning
based on the arguments you use with the
method

38

Overloading Methods

An overloaded method

39

Initializing an Array
Arrays, like object fields, have default values
You can assign nondefault values to array
elements upon creation
Examples:
int[] myScores = new int[5] {100,76,88,100,90};
int[] myScores = new int[] {100,76,88,100,90};
int[] myScores = {100,76,88,100,90};

40

Arrays
Arrays must be declared with brackets
after the type:
int[] numbers = new int[20];
Can use foreach statement (like VB)
ForEach.cs
Params
Params.cs
41

Arrays
"Extra" array elements are not initialized to 0
IndexOutOfBoundsException becomes
IndexOutOfRangeException

You can change an array's size


int[] nums = new int[5];
nums = new int[10];
42

Garbage Collection
No need for a delete
command to clear up dynamic
arrays
C#s garbage collection
reclaims object space
automatically behind the
scenes
For efficiency, C# only runs
the garbage collection feature
when:
There are objects to recycle
There is a need to recycle them

43

The BinarySearch() Method


The BinarySearch() method finds a
requested value in a sorted array
This method accepts two arguments: an
array, and the field to be searched for
The method returns 1 if the value is not
found in the array, otherwise it returns the
index where the value is located

44

The BinarySearch() Method


This method does NOT work under the
following conditions:
If the array items are not arranged in ascending
order, the BinarySearch() method does not work
correctly
If the array holds duplicated values, then the
BinarySearch may not work
If you want to find a range match rather that an
exact match, the BinarySearch() method does not
work

45

The BinarySearch() Method

BinarySearch program
46

Using the Sort() and Reverse() Methods

The Sort() method arranges array items in ascending order

47

Using the Sort() and Reverse()


Methods

The Reverse() method reverses the order of items in an array

48

Using the Sort() and Reverse()


Methods

Output of MyTestScores
49

Classes
Static members cannot be used with
objects
Built-in components have "natural"
names - e.g., Label, not JLabel
No multiple constructors for
components like Label, Button, etc.
50

Understanding the this Reference


When instances of a class are created, the resulting
objects require separate memory locations in the
computer
In the following code, each object of Book would at
least require separate memory locations for title,
numPages, and Price

51

Understanding the this Reference


Unlike the class fields that are unique to each
instance, the methods of the class are shared
Although the methods are shared, there must be a
difference between two method calls (from different
objects), because each returns a different value
(based on their unique fields)
When a method is called, you automatically pass a
reference to the memory of the object into the
method
The implicitly passed reference is the this reference
52

Understanding the this Reference

Book class methods explicitly


using this reference
53

Understanding the this Reference

Book class method that requires explicit this reference

54

Understanding Constructor
Methods
A constructor method is a method that establishes
an object
Every class created is automatically supplied with a
public constructor method with no parameters
Any constructor method you write must have the
same name as its class, and constructor methods
cannot have a return type

55

Inheritance
Use a colon (not "extends" or
"implements")
Classes can appear in any order and
within the same file (no forward
references)
When child class method overrides
parent class method you must use the
keyword new or override
56

Extending Classes
When you create a class that is an extension or
child of another class, you use a single colon
between the derived class name and its base
class name

57

You might also like