Содержание

Слайд 2

Your First C# Program

Our first C# program is a real classic. It

Your First C# Program Our first C# program is a real classic.
does nothing more than print a welcome message to the screen. Yet, t

Слайд 3

This program sends the simple greeting to the console

// Example1_1.cs
// This program

This program sends the simple greeting to the console // Example1_1.cs //
sends a simple greeting to the console
//
using System;
namespace csbook.ch1
{
class Example1_1
{
static void Main(String [] args)
{
Console.WriteLine("Welcome to C# Programming.");
}
}
}

Comments

using the System namespace

Creating namespace

The Main method

Class definition

When you execute that program and if all goes well you should
have a new file in your directory named Example1_1.exe. If you run
that file you should see your welcome message print to the screen.

Слайд 4

A Closer Look to the strucure of C# program

In C#, as in

A Closer Look to the strucure of C# program In C#, as
other C-style languages, every statement must end in a semicolon (;)

Statements can be joined into blocks using curly braces { }.

Single-line comments begin with two forward slash characters (//), and multi-line comments begin with a slash and an asterisk (/*) and end with the same combination reversed (*/).

The first couple of lines have to do with namespaces, which are a way to group together associated classes.

The using statement specifies a namespace that the compiler should look at to find any classes that are referenced in your code but which aren’t defined in the current namespace.

All C# code must be contained within a class. The class declaration consists of
the class keyword, followed by the class name and a pair of curly braces. All code associated with the class should be placed between these braces.

Every C# executable (such as console applications, Windows applications, and Windows services) must have an entry point — the Main() method

Слайд 5

Variables in C#

We declare variables in C# using the following syntax:

DataType variableName;
//

Variables in C# We declare variables in C# using the following syntax:
or
DataType variableName1, variableName2;
//for exampleint

The compiler won’t actually let us use this variable until we have initialized it with a value, but the declaration allocates 4 bytes on the stack to hold the value.

variableName = value;

If we declare and initialize more than one variable in a single statement, all of the variables will be of the same data type

Don’t assign different data
types within a multiple variable declaration

Слайд 6

Initialization of Variables

Can’t do this ! Need to initialize d befor use

Would

Initialization of Variables Can’t do this ! Need to initialize d befor
only create a reference for a Something object. But this reference does not yet actually refer to any object

Something objSomthing

Instantiating a reference object in C# requires use of the new keyword

objSomething = new So

Слайд 7

Variable scope

Variable scope

Слайд 8

Scope clashes for local variables
public static i
n
t Main(){ int j = 20;

Scope clashes for local variables public static i n t Main(){ int

We can’t do this:

Слайд 9

Scope clashes for fields and local variables

class ScopeTest2
{
static int j =

Scope clashes for fields and local variables class ScopeTest2 { static int
20; public st
a

We can do this:

What number will be displayed ?

class ScopeTest2
{
static int j = 20; public st
a

We can do this:

What number will be displayed ?

First case: the variable j in the Main() hides the class-level variable with the same name

Second case: We use the name of the class for static field j

Слайд 10

Constants

const int a = 10
0
; // This value cannot be chang
e

They must

Constants const int a = 10 0 ; // This value cannot
be initialized when they are declared, and once a value has been assigned, it can never be overwritten.

A constant is a variable whose value cannot be changed throughout its lifetime

Constants have the following characteristics:

We can’t initialize a constant with a value taken from a variable. If you need to do this, you will need to use a readonly field

Constants are always static. However, notice that we don’t have to include the static modifier in the constant declaration

Слайд 11

Statements

Programs consist of sequences of C# statements

Conditional statements

Loops

Statements allow us to control

Statements Programs consist of sequences of C# statements Conditional statements Loops Statements
the flow of our program rather than executing every line of code in the order it appears in the program

The switch statement

Jump statements

Слайд 12

Conditional statements

The if statement

One - way if
if ([condition]) [code to execute]
if ([condition])
{

Conditional statements The if statement One - way if if ([condition]) [code
[code to execute if condition is true]
}

if ([condition])
{
[code to execute if condition is true]
}
else
{
[code to execute if condition is false]
}

The conditional operator

Type result = [condition] ? [true expression] : [false expression]

Either – or if

Слайд 13

The switch statement

switch ([expression to check])
{
case [test1]:
...
[exit case statement]

The switch statement switch ([expression to check]) { case [test1]: ... [exit
case [test2]:
...
[exit case statement]
default:
...
[exit case statement]
}

Syntax
swith(a)
{
case 0:
// Executed if a is 0.
break;
case 1:
case 2:
case 3:
// Executed if a is 1, 2, or 3.
break;
default:
// Executed if a is any
// other value.
break;
}

Example

Слайд 14

Loops

C# provides four different loops

The for loop

The do … while loop

Loops allow

Loops C# provides four different loops The for loop The do …
us to execute a block of code repeatedly until a certain condition is met.

The while loop

The foreach loop

Слайд 15

The for loop

Syntax
for (int i = 0; i < 10; i++)
{
//

The for loop Syntax for (int i = 0; i { //
Code to loop, which can use i.
}
. . .
for (int i = 0; i < 10; i = +2)
{
// Code to loop, which can use i.
}
. . .
int j;
for (j = 0; j < 10; j++)
{
// Code to loop, which can use j.
}
// j is also available here

Example

Слайд 16

Nested loops

Example

static void Main(string[] args)
{
// This loop iterates through rows...
for

Nested loops Example static void Main(string[] args) { // This loop iterates
(int i = 0; i < 100; i+=10)
{
// This loop iterates through columns...
for (int j = i; j < i + 10; j++)
{
Console.Write(“ “ + j);
}
Console.WriteLine();
}
}

Слайд 17

The while loop

while ([condition])
{
[Code to loop]
}

Syntax
double balance = 100D;
double rate

The while loop while ([condition]) { [Code to loop] } Syntax double
= 2.5D;
double targetBalance = 1000D;
int years = 0;
while (balance <= targetBalance)
{
balance *= (rate / 100) + 1;
years += 1;
}

Example

Like the for loop, while is a pre-test loop. The syntax is similar, but while loops take only one expression

Unlike the for loop, the while loop is most often used to repeat a statement or a block of statements for a number of times that is not known before the loop begins.

Слайд 18

The do … while loop

The do...while loop is the post-test version of

The do … while loop The do...while loop is the post-test version
the while loop

This means that the loop’s test condition is evaluated after the body of the loop has been executed. This loop will at least execute once, even if Condition is false.

do
{
[Code to loop]
} while ([condition]);

Syntax

Example

Слайд 19

The foreach loop

The foreach loop allows us to iterate through each item

The foreach loop The foreach loop allows us to iterate through each
in a collection. The Collection is an object that contains other objects.

We can’t change the value of the item in the collection, so code such as the following will not compile:

fo
r
each (type [ item
] in [ collection ]{

Syntax

Example for C# arrays

CTE

Слайд 20

Jump statements

C# provides the number of statements that allow us to jump

Jump statements C# provides the number of statements that allow us to
to another line in the program

Br
e
ak can be used to
exit from for, foreach

The break statement

The continue statement
The return statement i
s
u
sed to exit a method of a class
, returning control to the ca
ller
of the method. If the method has a return type,
retur
n must return a value of this t

The return statement

Слайд 21

Classes and Structs

Classes and structs are templates form wich we can create

Classes and Structs Classes and structs are templates form wich we can
objects. Each object contain data and has methods to manipulate and access data.

Simple Class

Classes are reference type stored in the heap.
Struct are value type stored on the stack.

class PhoneCustomer
{
public const string DayOfSendingBill = “Monday”;
public int CustomerID;
public string FirstName;
public string LastName;
}

struct PhoneCustomer
{
public const string DayOfSendingBill = “Monday”;
public int CustomerID;
public string FirstName;
public string LastName;
}

Simple Struct

PhoneCustomer myCustomer = new PhoneCustomer();// works for a class
PhoneCustomer myCustomer = new PhoneCustomer(); // works for a struct

Слайд 22

Classes Members

Data members are those members that contain the data for the

Classes Members Data members are those members that contain the data for
class – fields, constants, and events.

Data members can be static (associated with the class as a whole).
Data members can be instance (each instance of the class has its own copy of the data).

Слайд 23

Classes Members

Fields are any variables associated with the class. We can access

Classes Members Fields are any variables associated with the class. We can
these fields using the Object.FieldName syntax

Events are class members that allow an object to notify a caller whenever something happens, such as a field property changing or something else.
The client can have a code known as an event handler that reacts to the event.

Constants can be associated with classes in the same way as variable. If it is declared as a public, it will be accessible from outside the class.

Слайд 24

Function Members

Function members are those members that provide some functionality for manipulating

Function Members Function members are those members that provide some functionality for
the data in the class. They include:

Methods are functions that are associated with a particular class. They can be instance or static methods ( like the Console.WriteLine() method).

Methods

Properties

Constructors

Finalizers

Operators

Indexers

Слайд 25

Declaring methods

The definition of the method consists: method modifiers, the type of

Declaring methods The definition of the method consists: method modifiers, the type
return value, the name of the method, a list of arguments, the body of the method

A method can contain as many return statements as required:

Слайд 26

Passing parameters to methods
class ParameterTest{ s
ta
t
ic void SomeFunction(int[] ints
, int i) {

Passing parameters to methods class ParameterTest{ s ta t ic void SomeFunction(int[]
ints[0] = 100
; i
= 100; }public static int Main(){ int i = 0;
int[]
ints = { 0, 1, 2, 4, 8 }; //

By reference

By value

Слайд 27

Ref parameters
// define method stati
c
v
oid SomeFunction(int[] ints, re
f int i) {

Ref parameters // define method stati c v oid SomeFunction(int[] ints, re
ints[0] = 10
0; i
= 100; } // We will also need to add the ref
when
we invoke the method

Passing variables by value is the default. We can, however, force value parameters to be passed by reference. To do so, we use the ref keyword. If a parameter is passed to a method, and if the input argument for that method is prefixed with the ref keyword, then any changes that the method makes to the variable will affect the value of the original object

Any variable must be initialized befor it is passed into a method, whether it is passed in by value or reference

Слайд 28

Out parameters
// define method stati
c
v
oid SomeFunction(out int i) {
i =

Out parameters // define method stati c v oid SomeFunction(out int i)
100; }public stati
c voi
d Main() { int i; // i is declared but not
init
ialized SomeFunction(out i)

C# requires that variables be initialized with a starting value before they are referenced. But if the method arguments is prefixed with out, that method can be passed a variable that has not been initialized. The variable is passed by reference

Слайд 29

Properties

The idea of a property is that it is a method or

Properties The idea of a property is that it is a method
pair of methods that are dressed to look like a field

Suppose you have the following code:

On executing this code, the height of the window will be set to 400 and you will see the window resize. The code looks like we are setting a field, but in fact we are calling a property accessor that contain code to resize the form.

Слайд 30

To define a property…

We use the following syntax:

The get accessor takes no

To define a property… We use the following syntax: The get accessor
parameters and must return the same type as the declared property.

Get accessor

Set accessor

Слайд 31

To define a property…
private string foreNam
e;
p
ublic string ForeName{ get { r
eturn foreName;

To define a property… private string foreNam e; p ublic string ForeName{
} set {
if
(value.Length > 20) // code here to take
error
recovery action // (eg.

Class field

Property

Example:

set works

get works

Имя файла: The-C-language-.pptx
Количество просмотров: 150
Количество скачиваний: 0