Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 75

Chapter 3

C# Essentials

1
Memory Concepts
• Variable names actually correspond to locations in the
computer’s memory.
• Every variable has a name, a type, a size and a value.
• In Figure below, the computer has placed the value 45
and 72 in the memory locations corresponding to
number1 and number2.

2
Memory Concepts (Cont.)
• After sum has been calculated, memory appears as shown in
figure below:

• Whenever a value is placed in a memory location, the value


replaces the previous value in that location, and the previous
value is lost.
3
Variables
• Provide a means to store data values that are not
stored in files.
• Represent locations in a computer's memory.
• are assigned a unique name for reference when
writing computer code.
• Values are stored to memory locations, The stored
values can vary over time.
• Each memory location is assigned a unique
variable name that is used to reference the
location when you write a program.

4
5
Variable Declaration
• A variable declaration specifies the name and type of a variable.
type name;
int sum;
– A variable’s name enables the application to access the value of the
variable in memory—the name can be any valid identifier.
– A variable’s type specifies what kind of information is stored at that
location in memory.
• Several variables of the same type may be declared in one
declaration.
type name1, name1, name2;
int number1, number2, sum;
• The variables can also be initialized when declared.
int sum = 0;
int number1 = 1, number2 = 2, sum = 0;
6
Variables cont’d
• Variables of type int store integer values (whole
numbers such as 7, –11, 0 and 31914).
• Types float, double and decimal specify real
numbers (numbers with decimal points).
• Type char represents a single character.
• These types are called simple types.
• Simple-type names are keywords and must
appear in all lowercase letters

7
Literals
Console.WriteLine("Hello World");
string literal
• Fixed (constant) values
– They cannot be changed during program’s execution
• They can be output by Console.WriteLine
• Different format for different types:
– String literals
• Sequences of characters
• Within double quotes (quotes are not part of the string)
• Almost any character is ok (letters, digits, symbols)
" 10 > 22 $&*%? "
– Numeric literals
• Integer
3 454 -43 +34
• Real
3.1415 +45.44 -54.6 1.2334e3
1.2334e3 is 1.2334 times 10 to the power 3 (scientific notation)
8
Identifiers
• Names of programmer defined elements in a program
– Names of classes, methods, variables, etc.
namespace World
{
public class HelloWorld
{
• Syntax (rules):
1. Sequence of letters (a .. z, A ..Z), digits (0 ..9) underscore _
2. Cannot start with a digit or underscore
3. Case-sensitive (number1 and Number1 are not the same)
• Examples:
Program1 valid
number_1 valid
mySum valid
1number not valid
• Pick meaningful names to improve readability and understandability
of your program (be consistent)
9
Keywords (reserved words)
• Special and fixed meanings
– built-in in C# language
– always spelled with all lowercase letters
• You cannot use a reserved word as a user-defined
identifier
• Cannot be changed by programmer
Examples:
– class,Using,namespace,static,void
• Identifiers may be preceded by the @ character to interpret a
keyword as an identifier (e.g. @class).

10
Console Output
• The backslash (\) is called an escape character, and is
used as the first character in an escape sequence.
Common Escape Sequences Description

\n Newline. Positions the screen cursor at the beginning of the


next line.

\t Horizontal tab. Moves the screen cursor to the next tab stop.

\r Carriage return. Positions the screen cursor at the beginning


of the current line—does not advance the cursor to the next
line.

\\ Backslash. Used to place a backslash character in a string.

\“ Double quote. Console.Write( "\"in quotes\"" ); displays "in


quotes"

11
Using Data Types
• Data types are used to store and represent data
in your application.
• The .NET languages are strongly typed.
• This means that objects of one type cannot be
freely exchanged with objects of a different type.
• All parameters in method and property calls
must be of the appropriate type, or the call will
fail.

12
Using Data Types cont’d
• The Microsoft .NET Framework provides a robust
system of primitive types to represent data.
• Data primitives exist for the representation of :
– integer numbers,
– floating-point numbers,
– Boolean values,
– characters and strings.
The type system enforces type-safety, so that implicit
casts only occur when no loss of data is possible.
Explicit conversions can be performed in situations that
might cause a loss of data.
13
Integer Types
Type Visual C# Name Description Range

System.Byte byte 8-bit unsigned integer 0 to 255

System.Int16 short 16-bit signed integer -32768 to 32767

System.Int32 int 32-bit signed integer -231 to 231-1

System.Int64 long 64-bit signed integer -263 to 263-1

System.SByte sbyte 8-bit signed integer -128 to 127

System.UInt16 ushort 16-bit unsigned integer 0 to 65535

System.UInt32 uint 32-bit unsigned integer 0 to 232-1

System.UInt64 ulong 64-bit unsigned integer 0 to 264-1

14
Floating-Point Types
Type Visual C# Name Description Precision Range (approximate)

32-bit
7 significant +/- 1.4 x 10-45 to
System.Single float floating-point
digits +/- 3.4 x 1038
variable

64-bit 15-16
+/- 5.0 x 10-324 to
System.Double double floating-point significant
+/- 1.7 x 10308
variable digits

128-bit
28 significant +/- 1.0 x 10-28 to
System.Decimal decimal floating-point
digits +/- 7.9 x 1028
variable

15
Floating-Point Types cont’d
• The System. Single type is appropriate for
floating-point calculations that require a lower
degree of precision.
• For greater levels of precision, you can use the
System.Double type. This provides a much
greater level of precision as well as the ability to
handle vastly larger values.
• The System.Decimal type is specifically designed
to facilitate financial calculations and is an ultra-
high precision variable..
16
Non-Numeric Types
System.Boolean
• The System.Boolean type is used to represent a value that is either true or
false.
System.Char
• The System.Char type represents a single instance of a 16-bit Unicode
character.
• You can assign a character literal to a variable of this type by enclosing the
literal in single quotes as follows:
char myChar;
myChar = 'W';
System.String
• The System.String type is a reference type, and it represents a series of Char
data types. A string can represent a word, a paragraph, a key value, or any other
string of characters.
string myString;
myString = "This is a String! Wow!";
17
Converting Types
• At times, you will need to convert data from one
type to another.
• Data can be converted in two ways:
• implicitly, which means the conversion is
performed automatically, and
• explicitly, which means you must specifically ask
for the conversion to be performed.

18
Converting Types cont’d
• Implicit Conversions:
• Implicit conversions between types are
automatically performed whenever the conversion
can be performed without the loss of data.
Example:
int anInteger = 100;
long aLong;
// Because a long can be assigned to every possible value of integer,
// there is no chance of losing data
aLong = anInteger;

19
Implicit Conversions in Visual C#
From To
short, ushort, int, uint, long, ulong, float, double,
byte
decimal
short int, long, float, double, decimal
int long, float, double, decimal
long float, double, decimal
float Double
char Int, uint, long, ulong, float, double, decimal
sbyte short, int, long, float, double, decimal
ushort int, uint, long, ulong, float, double, decimal
uint long, ulong, float, double, decimal
ulong float, double, decimal 20
Explicit Conversions
• This conversion is called a cast.
long aLong = 1000;
int anInteger;
anInteger = (int)aLong;
• Explicit conversions can be risky. the above conversion
was accomplished without any difficulty.
• However, consider the following example:
int anInteger = 100000;
short aShort;
aShort = (short)anInteger;
The code in this example will compile and execute without
raising an error. However, when you examine the value of
aShort, you find that it contains -31072. Because the
maximum value of aShort is smaller than the value that you
attempted to convert, it was unable to perform the
conversion, and a different value was put in its place.
21
Using Data Type Functionality
• All of the data types have some kind of built-in
functionality.
• At the very least, they all support four methods:
• Equals. Determines whether two instances are
equal
• GetHashCode. Serves as a hash function for a
particular type
• GetType. Returns the type object for the current
instance
• ToString. Returns a human-readable form of the
object
22
Data Type Member Methods
• Data types also have other methods that do not
derive from Object. These methods usually
involve functionality specific to the type.
Parse
• Parse is used to create a numeric value from a
string.
• Controls that accept user input, such as TextBox,
do so in the form of a string.
• The Parse method can be used to convert that
string to usable data.
• Note that if a string cannot be read as a numeric
value, an error will result.
23
• To convert a string to a numeric data type
Call the Parse method of that data type on that
method. An example follows
int I;
string S;
S = "1234";
// I = 1234
I = int.Parse(S);

24
String Functions
• The String class exposes a variety of member
methods for the manipulation of strings.
• They are divided between:
– instance methods, which return a string based
on the instance of the string they are called
from, and
– static methods, which must be called from the
String type.

25
Some Useful Instance String Methods
Name Description
String.Insert Inserts a specified string into the current instance
Adds characters to the left and right of the string,
String.PadLeft, String.PadRight
respectively
Deletes a specified number of characters from the string,
String.Remove
beginning at a specified character

Replaces all occurrences of a specified character in the


String.Replace
string with another specified character

Returns an array of substrings that are delimited by a


String.Split
specified character

String.Substring Returns a substring from the specified instance


String.ToCharArray Returns an array of the characters that make up the string
Returns the string converted to all lowercase or uppercase,
String.ToLower, String.ToUpper
respectively
String.TrimEnd, String.TrimStart, Removes trailing, leading, or both characters from the
String.Trim string, respectively 26
Some Useful Static String Methods
Name Description

String.Compare Compares two specified string objects

Returns a string that is the result of the


String.Concat
concatenation of two or more strings

Returns a string that has been formatted according


String.Format
to a specified format

Returns a string that is the result of the


concatenation of a specified array of strings, with a
String.Join
specified separation string between each member of
the array
27
Constants, Enums, Arrays, and Collections
• Arrays allow you to organize groups of similar
objects and refer to them by an index rather
than a name.
• Collections are similar to arrays but
implement advanced functionality and can be
used to organize dissimilar groups of objects
as well.
• Constants allow you to define user friendly
names to represent frequently used values.
• Enums allow you to organize sets of related
integral constants and use them to help make
your application easy to read and debug.
28
Constants and Enumerations
Using Constants
• Constants allow you to refer to frequently used values by friendly
names.
• use the const keyword to define a constant.
• For example: public const double Pi = 3.14159265;
• constants are of a fixed value that cannot be changed or redefined
once set. public const double Pi = 3.14159265;
public double CalculateCircleArea(double r)
{

return Pi * r * r;
}
• Use public keyword to make it acessible publically.
• To create a constant for internal use only, use the private keyword.
• The internal keyword specifies assembly level access, and the protected
keyword allows access by inheriting types.
29
Using Enumerations
• Enumerations allow you to work with sets of related constants and
to associate easy to remember names with those constants.
• The following demonstrates how to declare an enumeration:
• public enum DaysOfWeek
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
• The default data type for enums is int,but can be any data type.

30
Using Enumerations cont’d
• Because enumerations are user-defined types, you can create
methods that require enumeration members as values instead of
numeric values
public void ScheduleDayOff(day DaysOfWeek)
{
switch(day)
{
case DaysOfWeek.Monday:
// Implementation code omitted
break;
case DaysOfWeek.Tuesday:
// Implementation code omitted
break;
// Additional cases omitted
}
} 31
Arrays
• Arrays allow you to group a series of variables and
refer to them by an index.
• You can loop through all or part of the variables
and examine or affect each in turn.
• You can also create arrays with multiple
dimensions.
• Arrays in the .NET Framework have built-in
functionality to facilitate many of the common
tasks associated with arrays.

32
Declaring and Initializing Arrays
• Arrays can be declared and initialized in the same
statement.
• All arrays are zero based—meaning the index of
the first element is zero—and they are numbered
sequentially.
• The following example demonstrates how to
declare an array of integers:
// This line declares and initializes an array of 32 integers, with
// indexes ranging from 0 to 31
int[] myIntegers = new int[32];

33
Declaring and Initializing Arrays-cont’d
• Arrays can be declared and initialized in separate
steps.
// This line declares the array
int[] myIntegers;
// This line initializes the array with 32 members
myIntegers = new int[32];
You can change the size of your array at run time by
redefining it. This is as simple as reinitializing the
array as follows:
// This line declares and initializes the array
int[] myIntegers = new int[32];
// This line reinitialized the array
myIntegers = new int[45];
34
Declaring and Initializing Arrays-cont’d
// This example creates an array of Widgets, then assigns each
// variable to a Widget object
Widget[] Widgets = new Widget[11];
// Assigns Widgets[0] to a new Widget object
Widgets[0] = new Widget();
// Assigns Widgets[1] to an existing Widget object
Widget aWidget = new Widget();
Widgets[1] = aWidget;
// Loops through Widgets and assigns 2 through 10 to a new object
for (int Counter = 2; Counter < 11; Counter++)
{
Widgets[Counter] = new Widget();
} 35
Multidimensional Arrays
• The .NET Framework supports two kinds of multidimensional
arrays: rectangular arrays and jagged arrays.
1. Rectangular Arrays
• Rectangular arrays are arrays in which each member of each
dimension is extended in each other dimension by the same
length. i.e. All of the rows have the same number of columns.
• You declare a rectangular array by specifying additional dimensions
at declaration.
// Declares an array of 5 by 3 members
int[ , ] intArrays = new int[5, 3];
// Declares a two-dimensional array and sets initial values
int[ , ] intArrays = {{1, 2, 3}, {4, 5, 6}};
// Declares a cubical array and sets initial values
int[ , , ] cubeArray = {{{7, 2}, {1, 4}}, {{3, 5}, {4, 4}}};
// Declares a complex array of 3 x 3 x 4 x 5 x 6 members
int[ , , , , ] complexArray = new int[3, 3, 4, 5, 6];
36
Multidimensional Arrays cont’d
2. Jagged Arrays
• A two dimensional jagged array can be thought of as
a table where each row can have a different number
of columns.
• A jagged array is really an array of arrays.
• To create a jagged array, you declare the array of
arrays with multiple sets of parentheses or brackets
and indicate the size of the jagged array in the first
set of brackets (parentheses).

37
Multidimensional Arrays cont’d
• The following example demonstrates how to create a
simple jagged array:
// Declares an array of 3 arrays
string[][] Families = new string[3][];
// Initializes the first array to 4 members and sets values
Families[0] = new string[] {"Smith", "Mom", "Dad",
"Uncle Phil"};
// Initializes the second array to 5 members and sets values
Families[1] = new string[] {"Jones", "Mom", "Dad",
"Suzie", "Little Bobby"};
// Initializes the third array to 3 members and sets values
Families[2] = new string[] {"Williams", "Earl", "Bob"};

38
Collections
• A collection is a specialized class that organizes
and exposes a group of objects.
• Like arrays, members of collections can be
accessed by an index.
• Unlike arrays, however, collections can be resized
dynamically, and members can be added and
removed at run time.
• Collections are useful for managing groups of
items that are dynamically created at run time.

39
The ArrayList Class
• The System.Collections.ArrayList class provides
general collection functionality that is suitable for
most purposes.
• This class allows you to dynamically add and
remove items from a simple list.
• Items in the list are retrieved by accessing the
index of the item.
• You can create a new instance of the ArrayList
class as shown in the following example:
System.Collections.ArrayList myList = new System.Collections.ArrayList;

40
The Add Method
• Once instantiated, you can add items to the
ArrayList using the Add method, as follows:
Widget myWidget = new Widget;
myList.Add(myWidget);
• The list of objects managed by the ArrayList is a
zero-based collection.
• This means that the first object added to the list is
assigned the index zero, and every subsequently
added object is assigned to the next available
index.

41
The Item Property Indexer
• You can retrieve the item at a particular index by
using the Item property.
• In Visual C#, default properties are called indexers.
The following example demonstrates how to retrieve
a reference to an object in a collection.
object myObject;
myObject = myList[0];
• All references contained in a collection are of type
Object. Thus, the Item property returns a reference to
an Object regardless of the actual type of the object
contained therein. If you want to obtain a reference
of the same type as the object contained in the list,
you must explicitly cast the reference as follows:
Widget myWidget;
myWidget = (Widget)widgetCollection[0];
42
The Remove and RemoveAt Methods
• The Remove method requires a reference to an object
contained within the collection as a parameter and
removes that object from the collection.
For example:
Widget myWidget = new Widget();
System.Collections.ArrayList myList = new
System.Collections.ArrayList();
// Adds the Widget to the collection
myList.Add(myWidget);
// Removes the Widget from the collection
myList.Remove(myWidget);
• If you attempt to remove an object that is not contained
by a collection, you will not receive an error, but the line
43
will be ignored.
The Remove and RemoveAt Methods cont’d
• The RemoveAt method allows you to remove an object at a
particular index. For example:
System.Collections.ArrayList myList = new
System.Collections.ArrayList();
// Adds three widgets to the collection
for (int x = 0; x < 3; x++)
{
Widget myWidget = new Widget();
myList.Add(myWidget);
}
// Removes the Widget at index 1
myList.RemoveAt(1);
Note that as items are removed from a collection, the index
numbers are reassigned to occupy any available spaces.
Thus, index values are not static and might not always return
the same reference.
44
• The Count Property
The Count property returns the current number of items in a
collection. Because the collection index is zero based, the Count
property will always return one greater than the upper bound of
the array.

• Enumerating the Members of an Array or Collection

• Visual C# provide a specialized syntax for looping through the


members of an array or collection.
• The foreach statement allows you to examine each member of
an array or collection in turn. The syntax is as follows:
• int[] myArray = new int[] {1,2,3,4,5};
foreach (int I in myArray)
{
MessageBox.Show(I.ToString());
}

45
• When using this syntax with collections, you must ensure that
all members of the collection are of the same type as the
iteration variable. If you attempt to iterate through members of
a collection that cannot be assigned to the iteration variable, an
InvalidCastException will be thrown.
• To avoid this problem when working with collections that
contain different types of objects, declare the iteration variable
as an Object, and use the GetType method to determine if the
object is the correct type. An example follows:
// Assumes that myList is an ArrayList that contains Strings and
// a variety of objects of other types
foreach (object o in myList)
{
if (o.GetType() == typeof(string))
{
MessageBox.Show(o.ToString());
}
}

46
• It is important to note that when using the foreach
syntax, the reference that the iteration variable holds
to the members of the collection is read-only.
• Thus, you cannot use foreach to make changes to
items contained in an array or collection.
• If you want to loop through the members of your
array or collection and make changes to those
members, you should use a for loop, as demonstrated
in the following example:
int[] myArray = new int[] {1,2,3,4,5};
for (int x = 0; x <= myArray.GetUpperBound(0); x++)
{
myArray[x] ++;
MessageBox.Show(myArray[x].ToString());
}
47
Operators
1. Assignment Operator
• A value can be stored in a variable using the assignment
operator, =.
• Operator = is called a binary operator, because it works
on two pieces of information, or operands.
• An assignment statement assigns a value to a variable.
• Everything to the right of the assignment operator, =, is
always evaluated before the assignment is performed.
example:
int x, y, z;
x = y = z = 6;

48
2. Relational operators
• These operators let you compare two operands.
• When comparing numeric values, you usually
compare values with the same data type.
However, if you compare different types of
numeric values, C# will automatically cast the
value with the less precise type to the more
precise type.
• For example, if you compare an int value to a
decimal value, the int value will be cast to a
decimal value before the comparison is
performed. 49
Relational operators

50
• Examples
firstName = = "Frank" // equal to a string l
iteraltxtYears.Text = = "" // equal to an empty
stringmessage = = null // equal to a null
valuediscountPercent = = 2.3 // equal to a
numeric literalisValid == false // equal to the false
valuecode = = productCode // equal to another
variablelastName != "Jones" // not equal to string
literalyears > 0 // greater than a numeric literal
i < months // less than a variable
subtotal >= 500 // greater than or equal to a literal value
51
How to use the logical operators

52
Examples
subtotal >= 250 && subtotal < 500
timeInService <= 4 || timeInService >= 12
isValid == true & counter++ < years
isValid == true | counter++ < years
date > startDate && date < expirationDate || isValid == true
((thisYTD > lastYTD) || empType=="Part time") && startYear < currentYear
!(counter++ >= years)

53
54
control structures
• Control structures are used to manage the
program structure.
• Now, you’ll learn how to code the two types of
control structures that are common to all
modern programming languages:
– the selection(conditional), and
– iteration(loop) structures

55
Conditional Statements
• So far statements of our programs execute sequentially one
after another.
What happens when:
• we want to execute a statement depending on a condition?
e.g. If there is enough money in the bank account, give the
money
• we want to execute one statement when a condition holds
and another statement when a condition does not hold?
e.g. If dollar is high, sell dollar. Otherwise, buy dollar.
• we want to select from many statements according to one
or more criteria (selection).
e.g. If dollar is high and euro is low, sell dollar and buy euro. If
dollar is low and euro is high, sell euro and buy dollar. If both
of them are high, sell both and buy YTL.
• You achieve conditional execution with if-else statements
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

You might also like