Chapter3: fundamental programming
-
Upload
ngeam-soly -
Category
Education
-
view
1.428 -
download
0
description
Transcript of Chapter3: fundamental programming
Fundamental Programming with C#
C# Syntax
• Like C/C++ and Java
Identifiers
Identifiers (Cont.)
• Consist of Unicode characters
• Can begin with a letter or an
underscore
• Cannot a keywords
• eg. int, string, double, …
Capitalization Styles
• Pascal case, eg. MyValue
• Camel case, eg. myValueNumber
• Uppercase, eg. UI
Keywords
Literals
Operators
Punctuators
Statements
There are different kinds of statement in
C#:
• A code block
• Declaration statements
• Expression statements
• Selection statements
• Iteration statements
• Control statements
Comments
Types
Every piece of data in C# must have a type. This is a
key part of C# being a strongly typed programming
language. The C# compiler and runtime both use the
type of each data item to reduce some kinds of
programming problems.
There are two kinds of types in C#: value types and
reference types. The distinction between the two
causes programmers new to object-oriented
programming a lot of confusion.
Value Types
Value-type variables directly contain their data—
that is to say that the content of a value-type
variable is its value. The following statement
assigns a value of 25 to a variable called myInt. The
type of the variable myInt is int, which is a value
type.
Value Types (Cont.)
Reference Types
Reference types come in two parts—an object and the
reference to that object. Here is a statement that creates a
reference-type object:
StringBuilder myObject = new StringBuilder("Adam");
The StringBuilder type holds a string of characters. Figure 4-10
shows the reference type in memory. You don’t deal with the
object directly—instead, you work with it via the reference.
Definite Assignment and Null References
C# requires that you assign a value to a variable before you read the
value of the variable. The compiler checks your code to ensure that every
path through your code assigns a value to every variable that you read.
This is called definite assignment.
The assignment of a value doesn’t need to occur when you declare the
variable; you just have to make sure that you have made an assignment
before you read the variable value. Here are some statements that
demonstrate this:
int myInt; // declare a variable, but don't assign to it
myInt = 20; // assign a value to the variable
int sum = 100 + myInt; // we can read the value because we
have made an assignment
Common Programming TasksThe chapters that follow focus on the major
features of C#: classes, methods, fields,
parameters, delegates, and so on. These are such
important topics that it can be easy to overlook
the tasks that are most commonly required of
programmers. In the following sections, I describe
how to assign values to variables, make
comparisons between values, selectively execute
blocks of code, and iterate over data items.
Assigning Values
The C# assignment operator is the equals sign
(=). Figure 4-13 shows how the assignment
operator is used to assign a value to a variable.
Making Comparisions
The C# comparison operator (==) is used to
determine whether two variables are the same.
Making Comparisons (Cont.)
Performing Selections
Selection statements let you select blocks of code
statements to be executed if a condition is met. C#
supports two selection statements—the if statement
and the switch statement.
Using an if Statement
With an if statement, you define a block of code
statements that are performed only if a condition is
met.
Adding else if Clauses
You can choose between code blocks by adding else if
clauses to an if statement, like this:
if (x == 50) {
Console.WriteLine("First Code Block Selected");
} else if (x == 60) {
Console.WriteLine("Second Code Block
Selected");
} else if (x == 100) {
Console.WriteLine("Third Code Block Selected");
}
Adding an else clause
An if statement can contain a single else clause that will be
performed if the condition in the statement and all of the
conditions in any else if clauses evaluate to false. The else
clause must come at the end of the if statement, like this:
if (x == 100) {
Console.WriteLine("First Code Block Selected");
} else {
Console.WriteLine("Second Code Block
Selected");
}
Using a switch Statement
A switch statement selects one of a set of code statements to execute
by comparing a value to a set of constants.
string myName = "Adam Freeman";
switch (myName) {
case "Joe Smith":
Console.WriteLine("Name is Joe Smith");
break;
case "Adam Freeman":
Console.WriteLine("Name is Adam Freeman");
break;
default:
Console.WriteLine("Default reached");
break;
}
Using a switch Statement (Cont.)
Jumping to Another Switch SectionYou can combine the statements in switch sections by using a goto case statement, which jumps to the specified section, as follows:
switch (myName) {
case "Joe Smith":
Console.WriteLine("Name is Joe Smith");
break;
case "Adam Freeman":
Console.WriteLine("Name is Adam Freeman, Jane Jones or
Peter Kent");
goto case "Joe Smith";
default:
Console.WriteLine("Default reached");
break;
}
Iterating Data Items
One of the most common programming tasks is to perform the same series of actions for each element in a sequence of data items—for example, items in an array or a collection (see in next Chapter). C# supports four ways of performing iterations.
Using a for LoopA for loop repeatedly performs a block of statements while a condition remains true. Before the first iteration, an initializer executes one or more expressions. At the end of each iteration, an iterator executes one or more statements. Another iteration will be performed if the condition evaluates to true.
Breaking Out of a for Loop
You can terminate a for loop before the condition evaluates to false by using the break keyword, like this:
for (int i = 0; i < 100; i++) {
Console.WriteLine("Iteration for value: {0}", i);
if (i == 5) {
break;
}
}
Continuing to the Next IterationNormally a for loop will perform all the statements in the code block before moving on to the next iteration. By using the continue keyword, you can move to the next iteration without performing any statements that follow. Here is an example:
for (int i = 0; i < 5; i++) {
Console.WriteLine("Iteration for value: {0}", i);
if (i == 2 || i == 3) {
continue;
}
Console.WriteLine("Reached end of iteration for value:
{0}", i);
}
Using a do…while Loop
Using a while Loop
Numeric Types
C# has a number of predefined numeric types that can be referred to using keywords. I tend use the keywords, rather than the type names, but different programmers have varying styles, and it is useful to know how the keywords and the types relate to each other. There is no advantage in using one style over the other; the C# compiler converts the keywords into the correct type automatically, which means that you can mix keywords and types freely, even in the same code.
Numeric Types (Cont.)
Using Numeric Literals
C# allows you to define numeric values
literally so that you can just use the value of
the number in a statement, like this:
Using Numeric Operators
Numeric types have limited value on
their own; they need to be combined
with operators that allow you to
perform calculations and otherwise
manipulate the values they represent.
In the following sections, I describe the
five kinds of numeric operator that C#
supports.
Using Numeric Operators (Cont.)
Arithmetic Operators
C# includes basic arithmetic operators
that allow you to perform basic
calculations.
Unary Operators
The C# unary operators are so-called because they
work on a single numeric value.
Unary Operators (Cont.)
// define a number
float f = 26.765f;
// use the unary plus operator
float up = +f;
// use the unary minus operator
float um = -f;
// print out the results
Console.WriteLine("Unary plus result: {0}",
up);
Console.WriteLine("Unary minus result:
{0}", um);
Relational Operators
The C# relational operators allow you to
compare one numeric type to another.
Assignment Operators
With one exception, the assignment operators allow
you to conveniently apply one of the other
operators and assign the result in a single step.
Assignment Operators (Cont.)The assignment operators allow shorthand when you
want to perform an operation on a variable and
assign the result to the same variable. So, these
statements:
int x = 10;x = x + 2;
can be written as follows:
int x = 10;x += 2;
Classes and Objects
You create new functionality in
C# programs by defining
classes. Classes are the
blueprints used to create the
objects that you use to
represent items in your
program.
Creating a Basic Class
Remember that classes are the blueprints from which objects
are created. Imagine we had a blueprint for a car; for the sake
of an example, let’s say the blueprint is for a 2010 Volvo C30.
The blueprint specifies every detail of the car, but it isn’t a car
itself. It just describes how the car should be constructed. We
have to go through the process of constructing a car from the
blueprint to end up with something that we can get into and
drive away, and that something will be a Volvo C30, because
that’s what we used as the blueprint.
public class VolvoC30 {
// class body
}
Creating a Basic Class (Cont.)This class is so simple that it doesn’t do anything
yet, but we’ll add some features as we work
through.
Adding features to a Class
It is as though we wrote “Volvo C30” on a
blueprint and then just walked away. If we gave
the blueprint to someone else, they’d have only
the name to go on. We have not provided any
information about what features we require. We
add features to a class by adding class members.
There are a range of different categories of class
members, some of which are described in the
following sections. All of the different member
types are described in depth in the chapters that
follow.
Adding Fields
A field is a piece of information that each object created from
the class will have; this can be one of the built-in value types
that C# supports (such as a number or a Boolean value), or it
can be another object (a reference type). If a field refers to
another object, then that object can be one of those included
with the .NET Framework (such as a string), or it can be a type
we have created, like the VolvoC30 class.
public class VolvoC30 { public string CarOwner; public string PaintColor; public int MilesPerGallon= 30;}
Adding Methods
Methods let your object perform actions. That’s a
pretty wide definition, and the nature of your
methods will depend on the nature of your class. If
we remain with the car metaphor, then we could
have methods to start the engine, open the window,
plot a navigation route, and so on. If our class
represented a person, we might have methods that
change marital status, employment status, and
relationships, with objects representing other people.
Adding Methods (Cont.)public class VolvoC30 {
public string CarOwner;
public string PaintColor;
public int MilesPerGallon = 30;
public int CalculateFuelForTrip(int tripDistance) {
return tripDistance / MilesPerGallon;
}
public void PrintCarDetails() {
System.Console.WriteLine("--- Car Details ---");
System.Console.WriteLine("Car Owner: {0}",
CarOwner);
System.Console.WriteLine("Car Color: {0}",
PaintColor);
System.Console.WriteLine("Gas Mileage: {0} mpg",
MilesPerGallon);
}
}
Adding a Constructor
A constructor is a special method that you use when creating a new object,
allowing you to provide data via parameters that will set the initial state of the
object.
Creating Objects from ClassesObjects are often referred to as instances, for
example, “This object is an instance of the VolvoC30
class.” This is often shortened so that it is
commonly said that “This is an instance of
VolvoC30.” To create an object from a class, we use
the new operator, sometimes referred to as the
construction or instantiation operator. We tell the
new operator which class to work with, and it
creates a new object of the type representing by the
class.
Creating Objects from Classes (Cont.)
Using Objects
Once we have created an object, we can work with it
using the members we defined in the class. Working
with an object typically means doing one of two things:
changing the value of a field to change the state of an
object or using one of the objects methods to perform
an action. Methods can modify the value of fields as
well, so sometimes you’ll be performing a calculation
and modifying the state of an object in one go.
Reading and Modifying FieldsTo read the value of a field, we use the dot operator (.) to combine
the name we have given to the object instance and the name of
the field we want to access.
// create a new object of the VolvoC30 type
VolvoC30 myCar = new VolvoC30("Adam Freeman", "Black");
// create a second VolvoC30 object
VolvoC30 joesCar = new VolvoC30("Joe Smith", "Silver");
// read the value of the myCar.CarOwner field
string owner = myCar.CarOwner;
Console.WriteLine("Field value: {0}", owner);
Using Static Fields
The fields in all the examples in the previous sections have been instance
fields, meaning that each object has its own field. This is why we have to use
the object reference with the dot operator to access the field. We have to tell
the .NET runtime which object’s field we want to work with.
public class VolvoC30 {
public string CarOwner;
public string PaintColor;
public int MilesPerGallon = 30;
public static int EngineCapacity = 2000;
public VolvoC30(string newOwner, string paintColor) {
CarOwner = newOwner;
PaintColor = paintColor;
}
Using Static Fields (Cont.)
public int CalculateFuelForTrip(int tripDistance) {
return tripDistance / MilesPerGallon;
}
public void PrintCarDetails() {
System.Console.WriteLine("--- Car Details ---");
System.Console.WriteLine("Car Owner: {0}", CarOwner);
System.Console.WriteLine("Car Color: {0}", PaintColor);
System.Console.WriteLine("Gas Mileage: {0} mpg", MilesPerGallon);
System.Console.WriteLine("Engine Capacity: {0} cc", EngineCapacity);
}
}
Calling Methods
A new object doesn’t just get a set of fields and properties; it also gets its
own set of methods. In our VolvoC30 class, we defined two methods,
called PrintCarDetails and CalculateFuelForTrip.
public class VolvoC30 {
public string CarOwner;
public string PaintColor;
public int MilesPerGallon = 30;
public VolvoC30(string newOwner, string paintColor) {
CarOwner = newOwner;
PaintColor = paintColor;
}
Calling Methods (Cont.)
public void PrintCarDetails() {
System.Console.WriteLine("--- Car Details ---");
System.Console.WriteLine("Car Owner: {0}", CarOwner);
System.Console.WriteLine("Car Color: {0}", PaintColor);
System.Console.WriteLine("Gas Mileage: {0} mpg",
MilesPerGallon);
}
}
Using Access Modifiers
You can restrict the use of a class by applying an access modifier to the
class definition.