+ All Categories
Home > Education > Chapter3: fundamental programming

Chapter3: fundamental programming

Date post: 10-May-2015
Category:
Upload: ngeam-soly
View: 1,428 times
Download: 0 times
Share this document with a friend
Description:
មេរៀន C# ជំពូកទី៣
Popular Tags:
61
Fundamental Programming with C#
Transcript
Page 1: Chapter3: fundamental programming

Fundamental Programming with C#

Page 2: Chapter3: fundamental programming

C# Syntax

• Like C/C++ and Java

Page 3: Chapter3: fundamental programming

Identifiers

Page 4: Chapter3: fundamental programming

Identifiers (Cont.)

• Consist of Unicode characters

• Can begin with a letter or an

underscore

• Cannot a keywords

• eg. int, string, double, …

Page 5: Chapter3: fundamental programming

Capitalization Styles

• Pascal case, eg. MyValue

• Camel case, eg. myValueNumber

• Uppercase, eg. UI

Page 6: Chapter3: fundamental programming

Keywords

Page 7: Chapter3: fundamental programming

Literals

Page 8: Chapter3: fundamental programming

Operators

Page 9: Chapter3: fundamental programming

Punctuators

Page 10: Chapter3: fundamental programming

Statements

There are different kinds of statement in

C#:

• A code block

• Declaration statements

• Expression statements

• Selection statements

• Iteration statements

• Control statements

Page 11: Chapter3: fundamental programming

Comments

Page 12: Chapter3: fundamental programming

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.

Page 13: Chapter3: fundamental programming

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.

Page 14: Chapter3: fundamental programming

Value Types (Cont.)

Page 15: Chapter3: fundamental programming

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.

Page 16: Chapter3: fundamental programming

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

Page 17: Chapter3: fundamental programming

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.

Page 18: Chapter3: fundamental programming

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.

Page 19: Chapter3: fundamental programming

Making Comparisions

The C# comparison operator (==) is used to

determine whether two variables are the same.

Page 20: Chapter3: fundamental programming

Making Comparisons (Cont.)

Page 21: Chapter3: fundamental programming

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.

Page 22: Chapter3: fundamental programming

Using an if Statement

With an if statement, you define a block of code

statements that are performed only if a condition is

met.

Page 23: Chapter3: fundamental programming

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");

}

Page 24: Chapter3: fundamental programming

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");

}

Page 25: Chapter3: fundamental programming

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;

}

Page 26: Chapter3: fundamental programming

Using a switch Statement (Cont.)

Page 27: Chapter3: fundamental programming

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;

}

Page 28: Chapter3: fundamental programming

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.

Page 29: Chapter3: fundamental programming

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.

Page 30: Chapter3: fundamental programming

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;

}

}

Page 31: Chapter3: fundamental programming

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);

}

Page 32: Chapter3: fundamental programming

Using a do…while Loop

Page 33: Chapter3: fundamental programming

Using a while Loop

Page 34: Chapter3: fundamental programming

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.

Page 35: Chapter3: fundamental programming

Numeric Types (Cont.)

Page 36: Chapter3: fundamental programming

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:

Page 37: Chapter3: fundamental programming

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.

Page 38: Chapter3: fundamental programming

Using Numeric Operators (Cont.)

Page 39: Chapter3: fundamental programming

Arithmetic Operators

C# includes basic arithmetic operators

that allow you to perform basic

calculations.

Page 40: Chapter3: fundamental programming

Unary Operators

The C# unary operators are so-called because they

work on a single numeric value.

Page 41: Chapter3: fundamental programming

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);

Page 42: Chapter3: fundamental programming

Relational Operators

The C# relational operators allow you to

compare one numeric type to another.

Page 43: Chapter3: fundamental programming

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.

Page 44: Chapter3: fundamental programming

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;

Page 45: Chapter3: fundamental programming

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.

Page 46: Chapter3: fundamental programming

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

}

Page 47: Chapter3: fundamental programming

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.

Page 48: Chapter3: fundamental programming

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.

Page 49: Chapter3: fundamental programming

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;}

Page 50: Chapter3: fundamental programming

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.

Page 51: Chapter3: fundamental programming

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);

}

}

Page 52: Chapter3: fundamental programming

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.

Page 53: Chapter3: fundamental programming

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.

Page 54: Chapter3: fundamental programming

Creating Objects from Classes (Cont.)

Page 55: Chapter3: fundamental programming

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.

Page 56: Chapter3: fundamental programming

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);

Page 57: Chapter3: fundamental programming

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;

}

Page 58: Chapter3: fundamental programming

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);

}

}

Page 59: Chapter3: fundamental programming

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;

}

Page 60: Chapter3: fundamental programming

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);

}

}

Page 61: Chapter3: fundamental programming

Using Access Modifiers

You can restrict the use of a class by applying an access modifier to the

class definition.


Recommended