72
An Introduction to C# Dr. Hakem Beitollahi Computer Engineering Department Soran University Lecture 1

Lecture 1

Embed Size (px)

DESCRIPTION

OOP with C# by Dr.hakim

Citation preview

Page 1: Lecture 1

An Introduction to C#

Dr. Hakem Beitollahi

Computer Engineering DepartmentSoran University

Lecture 1

Page 2: Lecture 1

Objectives of this lecture In this chapter you will learn:

To write simple C# applications. To use input and output statements. C#’s primitive types. Basic memory concepts. To use arithmetic operators. The precedence of arithmetic operators. To write decision-making statements. To use relational and equality operators.

An introduction to C#— 2

Page 3: Lecture 1

First program in C#

An introduction to C#— 3

Page 4: Lecture 1

First C# program: printing a line

Single-line comments.

Predefined namespace (System)– part of .NET FCL

User defined namespace

User defined class

A blank line

Function Main appears exactly once in every C# program..

Left brace { begins function body.

Corresponding right brace } ends function body.

Function Main returns nothing (void) and is static

Statements end with a semicolon ;.

Console

An introduction to C#— 4

Page 5: Lecture 1

Elements of a C# Program

Page 6: Lecture 1

Anatomy of the first program (I)

Comments start with: // Comments ignored during program execution Document and describe code Provides code readability

Traditional comments: /* ... *//* This is a traditional comment. It can be split over many lines */

// First program in C#.

An introduction to C#— 6

Page 7: Lecture 1

Good Programming Practice Tip (1)

Every program should begin with a comment that explains the purpose of the program, the author and the date and time the program

Chapter 3: An introduction to C# — 7

Page 8: Lecture 1

using Directive

Permits use of classes found in specific namespaces without having to qualify them

Framework class library

Over 2,000 classes included

Syntax

using namespaceIdentifier;

An introduction to C#— 8

Page 9: Lecture 1

namespace One of the great strengths of C# is that C# programmers

can use the rich set of namespaces provided by the .NET These namespaces contain code that programmers can

reuse framework.Groups semantically related types under a

single umbrella System: most important and frequently used namespace

An example of one of the features in namespace System is Console

We discuss many namespaces and their features throughout the course.

An introduction to C#— 9

Page 10: Lecture 1

Blank line Use blank lines and space characters

throughout a program to make the program easier to read.

Collectively, blank lines, space characters, newline characters and tab characters are known as whitespace

The compiler ignores blank lines, tabs and extra spaces that

separate language elements.

An introduction to C#— 10

Page 11: Lecture 1

Our first class C# programs consist of pieces called classes, which are

logical groupings of members (e.g., methods) that simplify program organization.

These methods perform tasks and return information when the tasks are completed.

A C# program consists of classes and methods created by the programmer and of preexisting classes found in the Framework Class Library.

Every program in C# consists of at least one class definition that the programmer defines.

The class keyword begins a class definition in C# and is followed immediately by the class name (program)

An introduction to C#— 11

Page 12: Lecture 1

Identifiers names By convention, each word in a class name begins with an uppercase

first letter and has an uppercase letter for each word in the class name: SampleClassName

Identifiers is a series of characters consisting of letters, digits, underscores ( _ ) and “at” symbols (@).

Identifiers cannot begin with a digit and cannot contain spaces. The “at” character (@) can be used only as the first character in an

identifier Examples of valid identifiers:

Welcome1, _value, m_inputField1, button7, @value Examples of invalid identifiers

5welcome, input field, val@, in$put C# is case sensitive

An introduction to C#— 12

Page 13: Lecture 1

Common Programming Error (1)

C# is case sensitive. Not using the proper case for an identifier, e.g.,writing Total when the identifier is total, is a compiler error.

An introduction to C#— 13

Page 14: Lecture 1

Good Programming Practice Tip (2)

Always begin a class name with an uppercase first letter. This practice makes class names easier to identify.

An introduction to C#— 14

Page 15: Lecture 1

Braces { } The left brace ({) begins the body of the

class definition. The corresponding right brace (}) ends the

class definition.

An introduction to C# — 15

Page 16: Lecture 1

Common Programming Error Tip (2)

If braces do not occur in matching pairs, a syntax error occurs.

An introduction to C#— 16

Page 17: Lecture 1

Good Programming Practice Tip (3)

When typing an opening left brace ({) in a program, immediately type the closing right brace (}) then reposition the cursor between the braces to begin typing the body.

An introduction to C#— 17

Page 18: Lecture 1

Good Programming Practice Tip (4)

Indent the entire body of each class definition one “level” of indentation between the left brace ({) and the right brace (}) that delimit the class body. This emphasizes the structure of the class definition and helps make the class definition easier to read.

An introduction to C#— 18

Page 19: Lecture 1

static void Main(string[] args) present in all C# console and Windows applications. These applications begin executing at Main, which is

known as the entry point of the program. The parentheses after Main indicate that Main is a

program building block, called a method. C# class definitions normally contain one or more

methods and C# applications contain one or more classes.

For a C# console or Windows application, exactly one of those methods must be called Main

M in Main must be uppercase

Administrative — 19

Page 20: Lecture 1

The Console The Console class enables programs to output

information to the computer’s standard output. It provides methods to display strings and other types

of information in the Windows command prompt. Method Console.WriteLine displays (or prints) a line

of text in the console window. When Console.WriteLine completes its task, it

positions the output cursor at the beginning of the next line in the console window.

Statement: The entire line, including Console.WriteLine, its argument in the parentheses ("Welcome to C# Programming!") and the semicolon (;)

Every statement must end with a semicolon.Chapter 3: An introduction to C#— 20

Page 21: Lecture 1

Common Programming Error Tip (3)

Omitting the semicolon at the end of a statement is a syntax error.

When the compiler reports a syntax error, the error might not be on the line indicated by the error message. First, check the line where the error was reported. If that line does not contain syntax errors, check the lines that precede the one reported.

Chapter 3: An introduction to C#— 21

Page 22: Lecture 1

Administrative — 22

// Fig. 3.4: Welcome2.cs// Printing a line with multiple statements.

using System;

class Welcome2 { static void Main( string[] args ) { Console.Write( "Welcome to " ); Console.WriteLine( "C# Programming!" ); }}

Console.Write keeps the curse in the last position

Page 23: Lecture 1

Modifying the first program

(print same contents using different code)

An introduction to C#— 23

Page 24: Lecture 1

// Fig. 3.5: Welcome3.cs// Printing multiple lines with a single statement.

using System;

class Welcome3{ static void Main( string[] args ) { Console.WriteLine( "Welcome\nto\nC#\nProgramming!" ); }}

Notice how a new line is output for each \n escape sequence.

An introduction to C#— 24

Page 25: Lecture 1

Slash Operator (I)

An introduction to C#— 25

Page 26: Lecture 1

Slash Operator (II)

Code Meaning

\b Backspace

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab

\” Double quote

\\ backslash

\a Beep

26/27

Page 27: Lecture 1

The Same Program in Windows Form Style

An introduction to C#— 27

Page 28: Lecture 1

// Fig. 3.7: Welcome4.cs// Printing multiple lines in a dialog Box.

using System;using System.Windows.Forms;

class Welcome4 { static void Main( string[] args ) { MessageBox.Show("Welcome\nto\nC#\nprogramming!"); }}

Class MessageBoxis located in assembly System.Windows.Forms

An introduction to C#— 28

Page 29: Lecture 1

Common Programming Error Tip (4)

Including a namespace with the using directive, but not adding a reference to the proper assembly, results in a compiler error.

An introduction to C#— 29

Page 30: Lecture 1

Add a reference to your program (I)

To begin, make sure you have an application open. Select the Add Reference… option from the Project menu, or right click the References folder in the Solution Explorer and select Add Reference… from the popup menu that appears. This opens the Add Reference dialog. Double click System.Windows.Forms.dll to add this file to the Selected Components list at the bottom of the dialog, then click OK.

See next slide

An introduction to C#— 30

Page 31: Lecture 1

Add a reference to your program (II)

An introduction to C#— 31

Page 32: Lecture 1

GUI EXample

An introduction to C#— 32

Page 33: Lecture 1

Another Simple Program: Adding Integers

An introduction to C#— 33

Page 34: Lecture 1

Addition Proggram// Fig. 3.11: Addition.cs // An addition program. using System; class Addition { static void Main( string[] args ) { string firstNumber, // first string entered by user secondNumber; // second string entered by user int number1, // first number to add number2, // second number to add sum; // sum of number1 and number2  // prompt for and read first number from user as string Console.Write("Please enter the first integer: "); firstNumber = Console.ReadLine();  // read second number from user as string Console.Write("\nPlease enter the second integer: "); secondNumber = Console.ReadLine();  // convert numbers from type string to type int number1 = Int32.Parse( firstNumber ); number2 = Int32.Parse( secondNumber );  // add numbers sum = number1 + number2;  // display results Console.WriteLine( "\nThe sum is {0}.", sum ); } // end method Main} //end class Addition

Define two string variables to enter numbers

Define three integer variables

prompt for first number from user as string

Read first number from user as string usinf ReadLine method

convert numbers from type string to type int using Int32 class and Parse method

Add numbers

Display result in the screen

An introduction to C#— 34

Page 35: Lecture 1

Variables A variable is a location in the computer’s memory where

a value can be stored for use by a program. All variables must be declared with a name and a data

type before they can be used in a program. firstNumber and secondNumber are data of type string,

which means that these variables store strings of characters.

Primitive data types: string, int, double and char int holds integer values (whole numbers): i.e., 0, -4, 97 Types float and double can hold decimal numbers Type char can hold a single character: i.e., x, $, \n, 7

A variable name can be any valid identifier

An introduction to C#— 35

Page 36: Lecture 1

Good Programming Practice Tip (5)

Choosing meaningful variable names helps a program to be “self-documenting” (i.e., easier to understand simply by reading it, rather than having to read manuals or use excessive comments).

An introduction to C#— 36

Page 37: Lecture 1

Good Programming Practice Tip (6)

By convention, variable-name identifiers begin with a lowercase letter. As with class names, every word in the name after the first word should begin with a capital letter. For example, identifier firstNumber has a capital N in its second word, Number.

An introduction to C#— 37

Page 38: Lecture 1

Good Programming Practice Tip (7)

Some programmers prefer to declare each variable on a separate line. This format allows for easy insertion of a comment that describes each variable.

An introduction to C#— 38

Page 39: Lecture 1

Prompt

prompt the user to input an integer and read from the user a string representing the first of the two integers that the program will add.

It is called a prompt, because it directs the user to take a specific action.

Method ReadLine causes the program to pause and wait for user input.

The user inputs characters from the keyboard, then presses the Enter key to return the string to the program.

Console.Write("Please enter the first integer: "); firstNumber = Console.ReadLine();

An introduction to C#— 39

Page 40: Lecture 1

Convert string to int

Method Int32.Parse converts its string argument to an integer.

Class Int32 is part of the System namespace.

assign the integer that Int32.Parse returns to variable number1.

The = operator is a binary operator

// convert numbers from type string to type int number1 = Int32.Parse( firstNumber ); number2 = Int32.Parse( secondNumber );

An introduction to C#— 40

Page 41: Lecture 1

Good Programming Practice Tip (7)

Place spaces on either side of a binary operator. This makes the operator stand out and makes the program more readable.

An introduction to C#— 41

Page 42: Lecture 1

Sum

calculates the sum of the variables number1 and number2 and assigns the result to variable sum by using the assignment operator =.

// add numbers sum = number1 + number2;

An introduction to C#— 42

Page 43: Lecture 1

Display results (I)

It displays the result of the addition we want to output the value in a variable

using method WriteLine use {0} to indicate a placeholder for a

variable’s value. Suppose sum =117, the resulting string

will be “The sum is 117.”

// display results Console.WriteLine( "\nThe sum is {0}.", sum );

An introduction to C#— 43

Page 44: Lecture 1

Display results (II)

the value of number1 would replace {0} (because it is the first variable) and the value of number2 would replace {1} (because it is the second variable).

The resulting string would be "The numbers entered are 45 and 72".

More formats can be used ({2}, {3} etc.) if there are more variables to display in the string.

Console.WriteLine("The numbers entered are {0} and {1}", number1, number2);

An introduction to C#— 44

Page 45: Lecture 1

Good Programming Practice Tip (8)

Place a space after each comma in a method’s argument list to make programs more readable.

An introduction to C#— 45

Page 46: Lecture 1

Good Programming Practice Tip (9)

Follow the closing right brace (}) of the body of a method or class definition with a singleline comment. This comment should indicate the method or class that the right brace terminates.

An introduction to C#— 46

Page 47: Lecture 1

Memory Concepts

An introduction to C#— 47

Page 48: Lecture 1

Memory Concepts

45Number 1:

72Number 2:

117Sum:

Memory location showing the name and value of variable number1.Memory locations after storing values for number1 and number2.Memory locations after calculating and storing the sum of number1 and

number2.

An introduction to C#— 48

Page 49: Lecture 1

Arithmetic

An introduction to C#— 49

Page 50: Lecture 1

Arithmetic Operations (I)

An introduction to C#— 50

Page 51: Lecture 1

Be careful! 5 / 2 yields an integer 2 5.0 / 2 yields a double value 2.5

Remainder can be very useful Even numbers % 2 = 0 Today is Saturday and you and your friends are

going to meet in 10 days. What day is in 10 days?

Saturday is the 6th day in a week A week has 7 days

After 10 days

The 2nd day in a week is Tuesday (6 + 10) % 7 is 2

An introduction to C#— 51

Arithmetic Operations (II)

Page 52: Lecture 1

Arithmetic (III) Operators have precedence

Some arithmetic operators act before others (i.e., multiplication before addition)

Use parenthesis when needed Example: Find the average of three variables a, b and c

Do not use: a + b + c / 3 Use: ( a + b + c ) / 3

An introduction to C#— 52

Page 53: Lecture 1

Arithmetic (IV)

An introduction to C#— 53

Page 54: Lecture 1

Operators have precedence

1. Parentheses ()

2. *, /, %

3. +,-

4. …

3 + 4 * 4 + 5 * (4 + 3) – 1

3 + 4 * 4 + 5 * 7 – 1

3 + 16 + 5 * 7 – 1

3 + 16 + 35 – 1

19 + 35 – 1

54 – 1

53

in side parenthesis first

multiplication

multiplication

addition

addition

subtraction

An introduction to C#— 54

Arithmetic (V)

Page 55: Lecture 1

Algebra: z = pr%q + w/x – y

C#: z = p * r % q + w / x - y;

1

2

3

4

5

6

An introduction to C#— 55

Arithmetic (VI)

Page 56: Lecture 1

Test yourself y = a * x * x + b * x + c; Y = a+b/(a%5)-a%a*3; (a= 7, b = 3)

An introduction to C#— 56

Page 57: Lecture 1

Decision Making

An introduction to C#— 57

Page 58: Lecture 1

Decision Making: Equality and Relational Operators (I)

Condition Expression can be either true or false

if statement Simple version in this section, more detail later If a condition is true, then the body of the if

statement executed Control always resumes after the if statement Conditions in if statements can be formed

using equality or relational operators (next slide)

An introduction to C#— 58

Page 59: Lecture 1

Decision Making: Equality and Relational Operators (II)

An introduction to C#— 59

Page 60: Lecture 1

Common Programming Error Tip (5)

It is a syntax error if the operators ==, !=, >= and<= contain spaces between their symbols (as in = =, ! =, > =, < =).

An introduction to C#— 60

Page 61: Lecture 1

Common Programming Error Tip (6)

Reversing the operators !=, >= and <= (as in =!, => and =<) is a syntax error.

An introduction to C#— 61

Page 62: Lecture 1

Common Programming Error Tip (7)

Confusing the equality operator == with the assignment operator = is a logic error. The equality operator should be read “is equal to,” and the assignment operator should be read “gets” or “gets the value of.” Some people prefer to read the equality operator as “double equals” or “equals equals.”

An introduction to C#— 62

Page 63: Lecture 1

// Fig. 3.19: Comparison.cs // Using if statements, relational operators and equality operators. using System; class Comparison { static void Main( string[] args ) { int number1, // first number to compare number2; // second number to compare  // read in first number from user Console.Write("Please enter first integer: "); number1 = Int32.Parse(Console.ReadLine()); // read in second number from user Console.Write("\nPlease enter second integer: "); number2 = Int32.Parse(Console.ReadLine());  if (number1 == number2) Console.WriteLine(number1 + " == " + number2); if (number1 != number2) Console.WriteLine(number1 + " != " + number2); if (number1 < number2) Console.WriteLine(number1 + " < " + number2); if (number1 > number2) Console.WriteLine(number1 + " > " + number2); if (number1 <= number2) Console.WriteLine(number1 + " <= " + number2); if ( number1 >= number2 ) Console.WriteLine( number1 + " >= " + number2 );  }// end method Main} // end class Comparison

if structure compares values of num1 and num2 to test for equality. if structure compares values

of num1 and num2 to test for inequality.

If condition is true (i.e., values are equal), execute this statement.

If condition is true (i.e., values are not equal), execute this statement.

Directly get string and convert to int

An introduction to C#— 63

Page 64: Lecture 1

This expression uses the operator + to “add” (or combine) numbers and strings.

C# has a version of the + operator used for string concatenation.

Concatenation is the process that enables a string and a value of another data type (including another string) to be combined to form a new string.

Console.WriteLine(number1 + " == " + number2);

An introduction to C#— 64

Page 65: Lecture 1

Common Programming Error Tip (8)

Confusing the + operator used for string concatenation with the + operator used for addition can lead to strange results

Assume y = 5; The expression "y + 2 = " + y + 2 results in

the string "y + 2 = 52“ and not "y + 2 = 7". The expression "y + 2 = " + (y + 2) results

in "y + 2 = 7“

An introduction to C#— 65

Page 66: Lecture 1

Common Programming Error Tip (9)

Replacing operator == in the condition of an if structure, such as if ( x == 1 ), with operator =, as in if ( x = 1 ), is a logic error.

if (number1 = number2) Console.WriteLine(number1 + " == " + number2);

An introduction to C#— 66

Page 67: Lecture 1

Common Programming Error Tip (10)

Forgetting the left and right parentheses for the condition in an if structure is a syntax error. The parentheses are required.

if number1 == number2 Console.WriteLine(number1 + " == " + number2);

An introduction to C#— 67

( )

Page 68: Lecture 1

Common Programming Error Tip (11)

There is no semicolon (;) at the end of the first line of each if structure. It is Syntax error. If takes no action.

Example:

if (number1 == number2); Console.WriteLine(number1 + " == " + number2);

An introduction to C#— 68

Page 69: Lecture 1

Good Programming Practice Tip (10)

Place only one statement per line in a program. This enhances program readability.

An introduction to C#— 69

Page 70: Lecture 1

Good Programming Practice Tip (11)

A lengthy statement may be spread over several lines. In case of splitting, choose breaking points that make

sense, after a comma in a comma separated list after an operator in a lengthy expression.

Indent all subsequent lines with one level of indentation. Example:

int number1, // first number to add number2, // second number to add sum; // sum of number1 and number2

An introduction to C#— 70

Page 71: Lecture 1

Good Programming Practice Tip (12)

Confirm that the operators in the expression are performed in the expected order.

If you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order

assignment (=), associate from right to left rather than from left to right.

Example

y = a * x * x + b * x + c; y = (a * x * x) + (b * x) + c;

y = x; it means that x is assigned into y

An introduction to C#— 71

Page 72: Lecture 1

HomeWork First Homework Write a program in C# that print your name

with stars (*) in the screen

Deadline: Next week

* ** ** * * ** ** *

* * * ** ** * * ** ** *

* ** *** ** *

* * * * * * * * * * *** * * * *

* ** * * ** * * ** * * ** * *

An introduction to C#— 72