+ All Categories
Home > Documents > Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… ·...

Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… ·...

Date post: 29-Aug-2018
Category:
Upload: phamtram
View: 218 times
Download: 0 times
Share this document with a friend
96
1 Introduction to Microsoft .NET … .NET initiative Introduced by Microsoft (June 2000) Vision for embracing the Internet in software development Independence from specific language or platform Applications developed in any .NET compatible language Visual Basic .NET, Visual C++ .NET, C# and more Programmers can contribute to applications using the language in which they are most competent Architecture capable of existing on multiple platforms New program development process Provides increased productivity
Transcript
Page 1: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

1

Introduction to Microsoft .NET …• .NET initiative

– Introduced by Microsoft (June 2000)• Vision for embracing the Internet in software development

– Independence from specific language or platform• Applications developed in any .NET compatible language

– Visual Basic .NET, Visual C++ .NET, C# and more• Programmers can contribute to applications using the language in which

they are most competent– Architecture capable of existing on multiple platforms– New program development process

• Provides increased productivity

Page 2: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

2

Introduction to Microsoft .NET …• Key components of .NET

– Web services• Applications used over the Internet

– Software reusability• Web services provide solutions for wide variety of companies

– Cheaper than developing one-time solutions that can’t be reused– Single applications perform all operations for a company via various

Web services» Manage taxes, bills, investments, etc

• Pre-packaged components– Make application development quicker and easier– Developers no longer need to be concerned with details of components

Page 3: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

3

Introduction to Microsoft .NET …

• Keys to interaction– XML and SOAP

• “Glue” that combines various Web services to form applications

– XML gives meaning to data– SOAP allows communication to occur easily

• Additional information available at Microsoft Web site www.microsoft.com/net

Page 4: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

4

.NET Framework and the Common Language Runtime …

• .NET Framework– Heart of .NET

• Manages and executes applications and Web services• Provides security, memory management and other programming capabilities

– Includes Framework class library (FCL)• Pre-packaged classes ready for reuse• Used by any .NET language

– Executes programs by Common Language Runtime (CLR) (analogous to Java’s Virtual Machine, JVM)

– Details contained in Common Language Specification (CLS)• Submitted to European Computer Manufacturers Association to make the

framework easily converted to other platforms

Page 5: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

5

.NET Framework and the Common Language Runtime …

• Common Language Runtime (CLR)– Central part of framework

• Executes Visual Basic .NET programs– Compilation process

• Two compilations take place– Programs compiled to Microsoft Intermediate Language

(MSIL)» Defines instructions for CLR

– MSIL code translated into machine code» Machine code for a particular platform

Page 6: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

6

.NET Framework and the Common Language Runtime …/

• Why two compilations?– Platform independence

• .NET Framework can be installed on different platforms• Execute .NET programs without any modifications to code

– Language independence• .NET programs not tied to particular language• Programs may consist of several .NET-compliant languages• Old and new components can be integrated

• Other advantages of CLR– Execution-management features

• Manages memory, security and other features– Relieves programmer of many responsibilities– More concentration on program logic

Page 7: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

7

JVM (Java) vs CLR (.NET) : multiple platforms vs multiple languages.

Page 8: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

8

VISUAL STUDIO.NET Introduction

• Visual Studio .NET (VS.NET -- current version is VS2008)

– Microsoft’s Integrated Development Environment (IDE)

– Program in a variety of .NET languages– Tools to edit and manipulate several file types

Page 9: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

9

Visual Studio .NET Integrated Development Environment (IDE) Overview

Start Page in Visual Studio .NET.

navigation buttons

location bar

recent projects

buttons

hidden window

Start Pagelinks

Toolbox (for GUIs)

Page 10: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

10

How to obtain Visual Studio (VS)

• Available to use in dept. Labs. • Can download “express editions” (see

links in course web site) [ each express edition is good for specific tasks, e.g., C# programming, VB.NET programming, ASP.NET apps, etc]

• Can get a copy (per group) of full VS2008 from the dept.

Page 11: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

11

(C-sharp)

(many of these slides are extracted and adapted from Deitel’s book and slides, “How to Program in C#”. They are provided for CSE3403 students only. Not to be

published or publicly distributed without permission by the publisher).

Page 12: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

12

C#• C#

– Developed at Microsoft by a team led by Anders Hejlsberg and Scott Wiltamuth (June 2000)

– Event driven, object oriented, visual programming language.

– Based on C, C++ and Java.– Incorporated into .NET platform

• Web based applications can be distributed– Devices and desktop computers

• Programs that can be accessed by anyone through any device

• Allows communicating with different computer languages

Page 13: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

13

What you need to develop C# programs

• Either Visual Studio .NET, or • The .NET SDK

– Command line development– Download from (http://www.microsoft.com/downloads)– http://www.microsoft.com/downloads/details.aspx?Fa

milyID=333325fd-ae52-4e35-b531-508d977d32a6&DisplayLang=en

• Or the “C# express edition”.

Page 14: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

14

Introduction

• Console applications– No visual components– Only text output– Two types

• MS-DOS prompt– Used in Windows pre-Win2000 (95/98/ME)

• Command prompt– Used in windows post-Win2000 (2000/NT/XP/Vista)

– Windows applications• Forms with several output types• Contain Graphical User Interfaces (GUIs)

Page 15: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

15

Building non-windows applications (programs that only output to the command line and contain no GUI

components).

Page 16: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

16

Simple Program: Printing a Line of Text

Visual Studio .NET-generated console application.

Page 17: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

17

Or can use any text editor and type your program (good for when new to programming in general … but not really for now)

Upon typing the ‘.’, VS gives

options available …

Page 18: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

18

The final program

Page 19: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

19

Compile and Run

Compile (and produce .exe)

Run

Page 20: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

20

The output

Page 21: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

21

Welcome1.cs

Program Output

1 // Welcome1.cs2 // A first program in C#.34 using System;56 class Welcome1 //optionally public class Welcome17 {

8 static void Main( string[] args ) 9 // or public static void Main(…)

9 {10 Console.WriteLine( "Welcome to C# Programming!" );11 }12 }

Welcome to C# Programming!

Page 22: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

22

Simple Program: Printing a Line of Text

Execution of the Welcome1 program.

Page 23: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

23

Simple Program: Printing a line of text

• Comments– Comments can be created using //…– Multi-lines comments use /* … */– Comments are ignored by the compiler– Used only for human readers

• Namespaces– Groups related C# features into a categories– Allows the easy reuse of code– Many namespaces are found in the .NET framework library– Must be referenced in order to be used

• White Space– Includes spaces, newline characters and tabs

Page 24: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

24

Simple Program: Printing a line of text

• Keywords– Words that cannot be used as variable or class names or any other

capacity– Have a specific unchangeable function within the language– Example: class– All keywords are lowercase

• Classes– Class names can only be one word long (i.e. no white space in class

name )– Class names are capitalized, with each additional English word

capitalized as well (e.g., MyFirstProgram )– Each class name is an identifier

• Can contain letters, digits, and underscores (_)• Cannot start with digits• Can start with the at symbol (@)

Page 25: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

25

Simple Program: Printing a line of text

– Class bodies start with a left brace ({)– Class bodies end with a right brace (})

• Methods– Building blocks of programs– The Main method

• Each console or windows application must have exactly one• All programs start by executing the Main method

– Braces are used to start ({) and end (}) a method• Statements

– Anything in quotes (“) is considered a string– Every statement must end in a semicolon (;)

Page 26: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

26

Welcome2.cs

Program Output

1 // Welcome2.cs

2 // Printing a line with multiple statements.

3

4 using System;

5

6 class Welcome2

7 {

8 static void Main( string[] args )

9 {

10 Console.Write( "Welcome to " );

11 Console.WriteLine( "C# Programming!" );

12 }

13 }

Welcome to C# Programming!

Page 27: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

27

Welcome3.cs

Program Output

1 // Welcome3.cs

2 // Printing multiple lines with a single statement.

3

4 using System;

5

6 class Welcome3

7 {

8 static void Main( string[] args )

9 {

10 Console.WriteLine( "Welcome\nto\nC#\nProgramming!" );

11 }

12 }

WelcometoC#Programming!

Page 28: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

28

Simple Program: Printing a Line of Text

Escape sequence Description \n Newline. Position the screen cursor to the beginning of the

next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor to the beginning

of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the previous characters output on that line.

\\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double quote (") character.

Some common escape sequences.

Page 29: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

29

Another Simple Program: Adding Integers

• Primitive data types– Data types that are built into C#

• String, Int, Double, Char, Long• 15 primitive data types

– Each data type name is a C# keyword– Same type variables can be declared on separate lines or on one line

• Console.ReadLine()

– Used to get a value from the user input• Int32.Parse()

– Used to convert a string argument to an integer– Allows math to be performed once the string is converted

Page 30: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

30

Addition.cs1 // Fig. 3.11: Addition.cs

2 // An addition program.

3

4 using System;

5

6 class Addition

7 {

8 static void Main( string[] args )

9 {

10 string firstNumber, // first string entered by user

11 secondNumber; // second string entered by user

12

13 int number1, // first number to add

14 number2, // second number to add

15 sum; // sum of number1 and number2

16

17 // prompt for and read first number from user as string

18 Console.Write( "Please enter the first integer: " );

19 firstNumber = Console.ReadLine();

20

Read user’s input

Page 31: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

31

Addition.cs (cont’d)

21 // read second number from user as string

22 Console.Write( "\nPlease enter the second integer: ");

23 secondNumber = Console.ReadLine();

24

25 // convert numbers from type string to type int

26 number1 = Int32.Parse( firstNumber ); // Parse converts the given string to integer

27 number2 = Int32.Parse( secondNumber );

28

29 // add numbers

30 sum = number1 + number2;

Page 32: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

32

Addition.cs (cont’d)

Program Output

32 // display results33 Console.WriteLine( "\nThe sum is {0}.", sum );34 35 } // end method Main36 37 } // end class Addition

Please enter the first integer: 45

Please enter the second integer: 72

The sum is 117.

Page 33: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

33

Decision Making: Equality and Relational Operators

• The if structure– Used to make a decision based on the truth of the condition

• True: a statement is performed• False: the statement is skipped over

– The start of an if statement should not end in a semicolon (;)

Page 34: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

34

Decision Making: Equality and Relational Operators

Standard algebraic equality operator or relational operator

C# equality or relational operator

Example of C# condition

Meaning of C# condition

Equality operators = == x == y x is equal to y ≠ != x != y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y ≥ >= x >= y x is greater than or equal to y ≤ <= x <= y x is less than or equal to y

Equality and relational operators.

Page 35: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

35

Comparison.cs

1 // Comparison.cs2 // Using if statements, relational operators and equality3 // operators.4 5 using System;6 7 class Comparison8 {9 static void Main( string[] args )10 {11 int number1, // first number to compare12 number2; // second number to compare13 14 // read in first number from user15 Console.Write( "Please enter first integer: " );16 number1 = Int32.Parse( Console.ReadLine() );17 18 // read in second number from user19 Console.Write( "\nPlease enter second integer: " );20 number2 = Int32.Parse( Console.ReadLine() );21 22 if ( number1 == number2 )23 Console.WriteLine( number1 + " == " + number2 );24 25 if ( number1 != number2 )26 Console.WriteLine( number1 + " != " + number2 );27 28 if ( number1 < number2 )29 Console.WriteLine( number1 + " < " + number2 );30 31 if ( number1 > number2 )32 Console.WriteLine( number1 + " > " + number2 );33

Page 36: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

36

Comparison.cscont’d

34 if ( number1 <= number2 )

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

36

37 if ( number1 >= number2 )

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

39

40 } // end method Main

41

42 } // end class Comparison

Page 37: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

37

Program Output

Please enter first integer: 1000

Please enter second integer: 10001000 == 10001000 <= 10001000 >= 1000

Please enter first integer: 1000

Please enter second integer: 20001000 != 20001000 < 20001000 <= 2000

Please enter first integer: 2000

Please enter second integer: 10002000 != 10002000 > 10002000 >= 1000

Page 38: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

38

Decision Making: Equality and Relational Operators

Operators Associativ ity Type () left to right parentheses * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Precedence and associativ ity of operators discussed in this chapter.

Page 39: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

39

while Repetition Structure

• Repetition Structure– An action is to be repeated

• Continues while statement is true• Ends when statement is false

– Contain either a line or a body of code• Must alter conditional

– Endless loop

Page 40: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

40

Average1.cs1 // Average1.cs2 // Class average with counter-controlled repetition.3 4 using System;5 6 class Average17 {8 static void Main( string[] args )9 {10 int total, // sum of grades11 gradeCounter, // number of grades entered12 gradeValue, // grade value13 average; // average of all grades14 15 // initialization phase16 total = 0; // clear total17 gradeCounter = 1; // prepare to loop18 19 // processing phase20 while ( gradeCounter <= 10 ) // loop 10 times21 {22 // prompt for input and read grade from user23 Console.Write( "Enter integer grade: " );24 25 // read input and convert to integer26 gradeValue = Int32.Parse( Console.ReadLine() );27

Page 41: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

41

Average1.cscont’d

28 // add gradeValue to total29 total = total + gradeValue;30 31 // add 1 to gradeCounter32 gradeCounter = gradeCounter + 1;33 }

35 // termination phase36 average = total / 10; // integer division37 38 // display average of exam grades39 Console.WriteLine( "\nClass average is {0}", average );40 41 } // end Main42 43 } // end class Average1

Enter integer grade: 100Enter integer grade: 88Enter integer grade: 93Enter integer grade: 55Enter integer grade: 68Enter integer grade: 77Enter integer grade: 83Enter integer grade: 95Enter integer grade: 73Enter integer grade: 62

Class average is 79

Page 42: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

42

for Repetition Structure

• The for repetition structure– Syntax: for (Expression1, Expression2, Expression3)

• Expression1 = names the control variable– Can contain several variables

• Expression2 = loop-continuation condition• Expression3 = incrementing/decrementing

– If Expression1 has several variables, Expression3 must have several variables accordingly

– ++counter and counter++ are equivalent– Variable scope

• Expression1 can only be used in the body of the for loop• When the loop ends the variable expires

Page 43: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

43

for Repetition Structure

for ( int counter = 1; counter <= 5; counter++ )

Initial value of control variable Increment of control variable

Control variable name Final value of control variablefor keyword

Loop-continuation condition

Components of a typical for header.

Page 44: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

44

ForCounter.cs1 // ForCounter.cs

2 // Counter-controlled repetition with the for structure.

3

4 using System;

5

6 class ForCounter

7 {

8 static void Main( string[] args )

9 {

10 // initialization, repetition condition and incrementing

11 // are all included in the for structure

12 for ( int counter = 1; counter <= 5; counter++ )

13 Console.WriteLine( counter );

14 }

15 }

12345

Page 45: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

45

switch Multiple-Selection Structure

• The switch statement– Constant expressions

• String• Integral

– Cases• Case ‘x’ :

– Use of constant variable cases• Empty cases• The default case

– The break statement• Exit the switch statement

Page 46: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

46

SwitchTest.cs

1 // SwitchTest.cs

2 // Counting letter grades.

3

4 using System;

5

6 class SwitchTest

7 {

8 static void Main( string[] args )

9 {

10 char grade; // one grade

11 int aCount = 0, // number of As

12 bCount = 0, // number of Bs

13 cCount = 0, // number of Cs

14 dCount = 0, // number of Ds

15 fCount = 0; // number of Fs

16

Page 47: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

47

SwitchTest.cs …

17 for ( int i = 1; i <= 10; i++ )

18 {

19 Console.Write( "Enter a letter grade: " );

20 grade = Char.Parse( Console.ReadLine() );

21

22 switch ( grade )

23 {

24 case 'A': // grade is uppercase A

25 case 'a': // or lowercase a

26 ++aCount;

27 break;

28

29 case 'B': // grade is uppercase B

30 case 'b': // or lowercase b

31 ++bCount;

32 break;

33

Page 48: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

48

SwitchTest.cs …34 case 'C': // grade is uppercase C

35 case 'c': // or lowercase c

36 ++cCount;

37 break;

38

39 case 'D': // grade is uppercase D

40 case 'd': // or lowercase d

41 ++dCount;

42 break;

43

44 case 'F': // grade is uppercase F

45 case 'f': // or lowercase f

46 ++fCount;

47 break;

48

49 default: // processes all other characters

50 Console.WriteLine(

51 "Incorrect letter grade entered." +

52 "\nGrade not added to totals." );

53 break;

54

55 } // end switch

56

57 } // end for

Page 49: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

49

58

59 Console.WriteLine(

60 "\nTotals for each letter grade are:\nA: {0}" +

61 "\nB: {1}\nC: {2}\nD: {3}\nF: {4}", aCount, bCount,

62 cCount, dCount, fCount );

63

64 } // end method Main

65

66 } // end class SwitchTest

SwitchTest.cs …/

Page 50: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

50

SwitchTest.csProgram Output

Enter a letter grade: aEnter a letter grade: AEnter a letter grade: cEnter a letter grade: FEnter a letter grade: zIncorrect letter grade entered.Grade not added to totals.Enter a letter grade: DEnter a letter grade: dEnter a letter grade: BEnter a letter grade: aEnter a letter grade: C

Totals for each letter grade are:A: 3B: 1C: 2D: 2F: 1

Page 51: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

51

Statements break and continue

• Use– Used inside loops– Used to alter the flow of control– The break statement

• Used to exit a loop early– The continue statement

• Used to skip the rest of the statements and begin the loop at the first statement in the loop

– Programs can be completed without their usage

Page 52: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

52

BreakTest.cs1 // BreakTest.cs

2 // Using the break statement in a for structure.

3

4 using System;

..

7 class BreakTest

8 {

9 static void Main( string[] args )

10 {

11 string output = "";

12 int count;

13

14 for ( count = 1; count <= 10; count++ )

15 {

16 if ( count == 5 )

17 break;

20 output += count + " ";

21

22 } // end for loop

24 output += "\nBroke out of loop at count = " + count;

29 } // end method Main

31 } // end class BreakTest

skip remaining code in loop if count == 5

Page 53: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

53

ContinueTest.cs1 // ContinueTest.cs

2 // Using the continue statement in a for structure.

3

4 using System;

5 using System.Windows.Forms;

6

7 class ContinueTest

8 {

9 static void Main( string[] args )

10 {

11 string output = "";

12

13 for ( int count = 1; count <= 10; count++ )

14 {

15 if ( count == 5 )

16 continue; 19 output += count + " ";

20 }

22 output += "\nUsed continue to skip printing 5";

27 } // end method Main

29 } // end class ContinueTest

Skip remaining code in loop only if count == 5

Page 54: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

54

Logical and Conditional Operators

• Operators– Conditional AND (&&)– Conditional OR (||)– Logical exclusive OR or XOR (^)– Logical NOT (!)

• Can be avoided if desired by using other conditional operators

• Used to add multiple conditions to a statement

Page 55: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

55

Logical and Conditional Operators

expression1 expression2 expression1 && expression2

false false false false true false true false false true true true

Truth table for the && (logical AND) operator.

expression1 expression2 expression1 || expression2

false false false false true true true false true true true true

Truth table for the || (logical OR) operator.

Page 56: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

56

Logical and Conditional Operatorsexpression1 expression2 expression1 ^

expression2 false false false false true true true false true true true false

Truth table for the logical exclusiv e OR (^) operator.

expression !expression false true True false

Truth table for operator! (logical NOT).

Page 57: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

57

C# Namespaces

• Namespace (analogous to “Package” of Java) – A group of classes and their methods– The Framework Class Library (FCL) is composed of

namespaces– Namespaces are stored in .dll files called assemblies– A list of the FCL namespaces are shown next– Included in a program with the using keyword

Page 58: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

58

Some C# & .NET NamespacesNamespace Description System Contains essential classes and data types (such as int,

double, char, etc.). Implicitly referenced by all C# programs.

System.Data Contains classes that form ADO .NET, used for database access and manipulation.

System.Drawing Contains classes used for drawing and graphics. System.IO Contains classes for the input and output of data, such as with

files. System.Threading Contains classes for multithreading, used to run multiple parts

of a program simultaneously. System.Windows.Forms Contains classes used to create graphical user interfaces. System.Xml Contains classes used to process XML data.

Some Namespaces in the Framework Class Library.

Page 59: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

59

The C# (and .NET in general) API

Choose …

Page 60: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

60

…/

System is a major namespace for C#

Page 61: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

61

How to access the C# API (and the .NET API, in general)

1

2

Page 62: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

62

3

Page 63: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

63

4

Page 64: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

64

Page 65: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

65

Program Modules in C#• Modules

– Class– Method

• To display to screen from within program (for now):– Console– MessageBox

Page 66: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

66

Math Class Methods

• The Math class– Allows the user to perform common math calculations– Using methods

• ClassName.MethodName( argument1, arument2, … )

– Constants• Math.PI = 3.1415926535…• Math.E = 2.7182818285…

Page 67: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

67

Math Class MethodsMethod Description Example Abs( x ) absolute value of x Abs( 23.7 ) is 23.7

Abs( 0 ) is 0 Abs( -23.7 ) is 23.7

Ceiling( x ) rounds x to the smallest integer not less than x

Ceiling( 9.2 ) is 10.0 Ceiling( -9.8 ) is -9.0

Cos( x ) trigonometric cosine of x (x in radians)

Cos( 0.0 ) is 1.0

Exp( x ) exponential method ex Exp( 1.0 ) is approximately 2.7182818284590451 Exp( 2.0 ) is approximately 7.3890560989306504

Floor( x ) rounds x to the largest integer not greater than x

Floor( 9.2 ) is 9.0 Floor( -9.8 ) is -10.0

Log( x ) natural logarithm of x (base e) Log( 2.7182818284590451 ) is approximately 1.0 Log( 7.3890560989306504 ) is approximately 2.0

Max( x, y ) larger value of x and y (also has versions for float, int and long values)

Max( 2.3, 12.7 ) is 12.7 Max( -2.3, -12.7 ) is -2.3

Min( x, y ) smaller value of x and y (also has versions for float, int and long values)

Min( 2.3, 12.7 ) is 2.3 Min( -2.3, -12.7 ) is -12.7

Pow( x, y ) x raised to power y (xy) Pow( 2.0, 7.0 ) is 128.0 Pow( 9.0, .5 ) is 3.0

Sin( x ) trigonometric sine of x (x in radians)

Sin( 0.0 ) is 0.0

Sqrt( x ) square root of x Sqrt( 900.0 ) is 30.0 Sqrt( 9.0 ) is 3.0

Tan( x ) trigonometric tangent of x (x in radians)

Tan( 0.0 ) is 0.0

Commonly used Math class methods.

Page 68: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

68

Method Definitions• Writing a custom method

– Header• ReturnType Properties Name( Param1, Param2, … )

– Body• Contains the code of what the method does• Contains the return value if necessary

– For uses call elsewhere in program• Pass parameters if needed

– All methods must be defined inside of a class

Page 69: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

69

MaximumValue.cs1 // MaximumValue.cs2 // Finding the maximum of three doubles.4 using System;56 class MaximumValue7 {8 static void Main( string[] args )10 {11 // obtain user input and convert to double12 Console.Write( "Enter first floating-point value: " );13 double number1 = Double.Parse( Console.ReadLine() ); 15 Console.Write( "Enter second floating-point value: " );16 double number2 = Double.Parse( Console.ReadLine() ); 18 Console.Write( "Enter third floating-point value: " );19 double number3 = Double.Parse( Console.ReadLine() ); 21 // call method Maximum to determine largest value22 double max = Maximum( number1, number2, number3 );24 // display maximum value25 Console.WriteLine("\nmaximum is: " + max );27 } // end method Main

Page 70: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

70

2829 // Maximum method uses method Math.Max to help determine30 // the maximum value31 static double Maximum( double x, double y, double z )32 {33 return Math.Max( x, Math.Max( y, z ) );3435 } // end method Maximum3637 } // end class MaximumValue

Enter first floating-point value: 37.3Enter second floating-point value: 99.32Enter third floating-point value: 27.1928

maximum is: 99.32

Page 71: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

71

Argument Promotion• Implicit Conversion

– Object is converted to a needed type implicitly– Only done if complier knows no data will be lost

• Explicit Conversion– Object is manually converted– Required if there could be a loss of data– Widening

• Make an object that of a derived class and more complex– Narrowing

• Make an object that of a base class and cause some data loss

Page 72: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

72

Argument PromotionType Can be Converted to Type(s) bool object

byte decimal, double, float, int, uint, long, ulong, object, short or ushort

sbyte decimal, double, float, int, long, object or short char decimal, double, float, int, uint, long, ulong, object or ushort decimal object

double object

float double or object int decimal, double, float, long or object uint decimal, double, float, long, ulong, or object long decimal, double, float or object ulong decimal, double, float or object object None short decimal, double, float, int, long or object ushort decimal, double, float, int, uint, long, ulong or object string object

Allowed implicit conversions.

Page 73: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

73

Value Types and Reference Types

• Value types– Contains data of the specified type– Programmer created

• structs• enumerations

• Reference types– Contain an address to a spot in memory where the data is– Programmer created

• Classes• Interfaces • Delegates

• All values are 32bit allowing cross-platform use

Page 74: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

74

Passing Arguments: Call-By-Value vs. Call-By-Reference

• Passing by value– Send a method a copy of the object– When returned are always returned by value– Set by value by default

• Passing by reference– Send to the method the actual reference point

• Causes the variable to be changed throughout the program– When returned are always returned by reference– The ref keyword specifies by reference– The out keyword means a called method will initialize it

Page 75: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

75

RefOutTest.cs1 // RefOutTest.cs2 // Demonstrating ref and out parameters.34 using System;5 using System.Windows.Forms;67 class RefOutTest8 {9 // x is passed as a ref int (original value will change)10 static void SquareRef( ref int x )11 {12 x = x * x;13 }1415 // original value can be changed and initialized16 static void SquareOut( out int x )17 {18 x = 6; // method initializes x (“out” keyword)19 x = x * x;20 }2122 // x is passed by value (original value not changed)23 static void Square( int x )24 {25 x = x * x;26 }2728 static void Main( string[] args )29 {30 // create a new integer value, set it to 531 int y = 5;32 int z; // declare z, but do not initialize it33

Page 76: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

76

RefOutTest.cs34 // display original values of y and z35 string output1 = "The value of y begins as "36 + y + ", z begins uninitialized.\n\n\n";3738 // y and z are passed by reference39 RefOutTest.SquareRef( ref y );40 RefOutTest.SquareOut( out z );41 42 // display values of y and z after modified by methods43 // SquareRef and SquareOut44 string output2 = "After calling SquareRef with y as an " +45 "argument and SquareOut with z as an argument,\n" +46 "the values of y and z are:\n\n" + 47 "y: " + y + "\nz: " + z + "\n\n\n";48 49 // values of y and z are passed by value50 RefOutTest.Square( y );51 RefOutTest.Square( z );5253 // values of y and z will be same as before because Square54 // did not modify variables directly55 string output3 = "After calling Square on both x and y, " +56 "the values of y and z are:\n\n" +57 "y: " + y + "\nz: " + z + "\n\n";58 59 MessageBox.Show( output1 + output2 + output3, 60 "Using ref and out Parameters", MessageBoxButtons.OK,61 MessageBoxIcon.Information );62 63 } // end method Main64 65 } // end class RefOutTest

Page 77: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

77

RefOutTest.csProgram Output

Page 78: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

78

Random Number Generation

• Class Random– Within namespace System– Truly random

• The numbers are generated using an equation with a seed– The seed is usually the exact time of day

– randomObject.Next()• Returns a number from 0 to Int32.MaxValue

– Int32.MaxValue = 2,147,483,647

– randomObject.Next( x )• Returns a value from 0 up to but not including x

– randomObject.Next( x, y )• Returns a number between x and up to but not including y

Page 79: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

79

RandomInt.cs1 // RandomInt.cs; // Random integers.4 using System;5 using System.Windows.Forms;6 7 // calculates and displays 20 random integers8 class RandomInt9 {10 // main entry point for application11 static void Main( string[] args )12 {13 int value;14 string output = "";1516 Random randomInteger = new Random(); // create a new Random object18 // loop 20 times19 for ( int i = 1; i <= 20; i++ ) 20 {21 // pick random integer between 1 and 622 value = randomInteger.Next( 1, 7 ); // Will set value to a random number from 1 up to but not including 723 output += value + " "; // append value to output25 // if counter divisible by 5, append newline26 if ( i % 5 == 0 ) //Format the output to only have 5 numbers per line

27 output += "\n";29 } // end for30

Page 80: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

80

31 MessageBox.Show( output, "20 Random Numbers from 1 to 6",32 MessageBoxButtons.OK, MessageBoxIcon.Information );33 34 } // end Main35 36 } // end class RandomInt

Page 81: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

81

Duration of Identifiers• Duration

– The amount of time an identifier exist in memory

• Scope– The section of a program in which the object can be referenced

• Local variables– Created when declared– Destroyed when the block exits– Not initialized

• Most variables are set to 0• All bool variables are set to false• All reference variables are set to null

Page 82: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

82

Scope Rules

• Scope– Portion of a program in which a variable can be accessed– Class scope

• From when created in class• Until end of class (})• Global to all methods in that class

– Direct modification• Repeated names causes previous to be hidden until scope ends

– Block scope• From when created• Until end of block (})• Only used within that block

– Must be passed and modified indirectly• Cannot repeat variable names

Page 83: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

83

Scoping.cs1 // Fig. 6.13: Scoping.cs2 // A Scoping example.3 4 using System;5 using System.Drawing;6 using System.Collections;7 using System.ComponentModel;8 using System.Windows.Forms;9 using System.Data;11 public class Scoping : System.Windows.Forms.Form12 {13 private System.ComponentModel.Container components = null;14 private System.Windows.Forms.Label outputLabel;16 public int x = 1;17 18 public Scoping()19 {20 InitializeComponent();22 int x = 5; // variable local to constructor23 24 outputLabel.Text = outputLabel.Text +25 "local x in method Scoping is " + x;26 27 MethodA(); // MethodA has automatic local x;28 MethodB(); // MethodB uses instance variable x29 MethodA(); // MethodA creates new automatic local x30 MethodB(); // instance variable x retains its value31 32 outputLabel.Text = outputLabel.Text +33 "\n\nlocal x in method Scoping is " + x;34 }

This variable has class scope and can be used by any method in the class

This variable is local only to Scoping. It hides the value of the global variable

Will output the value of 5

Remains 5 despite changes to global version of x

Page 84: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

84

Scoping.cs35 38 public void MethodA()39 {40 int x = 25; // initialized each time a is called42 outputLabel.Text = outputLabel.Text +43 "\n\nlocal x in MethodA is " + x +44 " after entering MethodA";45 ++x;46 outputLabel.Text = outputLabel.Text +47 "\nlocal x in MethodA is " + x + 48 " before exiting MethodA";49 }51 public void MethodB()52 {53 outputLabel.Text = outputLabel.Text +54 "\n\ninstance variable x is " + x +55 " on entering MethodB";56 x *= 10;57 outputLabel.Text = outputLabel.Text + 58 "\ninstance varable x is " + x +59 " on exiting MethodB";60 }61 62 // main entry point for application63 [STAThread]64 static void Main() 65 {66 Application.Run( new Scoping() );67 }69 } // end of class Scoping

Uses the global version of x (1)

Uses a new x variable that hides the value of the global x

Will permanently change the value of x globally

Page 85: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

85

Scoping.csProgram Output

Page 86: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

86

Recursion

• Recursive methods– Methods that call themselves

• Directly• Indirectly

– Call others methods which call it

– Continually breaks problem down to simpler forms– Must converge in order to end recursion– Each method call remains open (unfinished)

• Finishes each call and then finishes itself

Page 87: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

87

public long Factorial( long number ){

if ( number <= 1 ) // base case; //The recursion ends when the value is less than or equal to 1

return 1;

elsereturn number * Factorial( number - 1 );

}

Page 88: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

88

Method Overloading

• Methods with the same name– Can have the same name but need different

arguments• Variables passed must be different

– Either in type received or order sent

Page 89: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

89

29 // first version, takes one integer30 public int Square ( int x )31 {32 return x * x;33 }34 35 // second version, takes one double

36 public double Square ( double y )37 {38 return y * y;39 }40

One method takes an int as parameters

The other version of the method uses a double instead of an integer

Page 90: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

90

Object-Based Programming

Page 91: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

91

Introduction• Object classes encapsulate (wrap together) data and

methods• Objects can hide implementation from other objects

(information hiding)• Methods : units of programming• Classes have

– Data members (member variable or instance variables)

– Methods that manipulate the data members

Page 92: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

92

• The opening left brace ({) and closing right brace (}) delimit the body of a class

• Variables inside the class definition but not a method definition are called instance variables

• Member Access Modifiers– public : member is accessible wherever an instance of

the object exists– private : members is accessible only inside the class

definition– (More later)

Page 93: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

93

• Access methods : read or display data• Predicate methods : test the truth of conditions• Constructor

– Initializes objects of the class– Can take arguments– Cannot return values– There may be more then one constructor per class (overloaded

constructors)

• Operator new used to instantiate classes (as in Java)• (in VS.NET Use Project < Add Class to add a new class to your

project

Page 94: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

94

Time1.cs1 // Time1.cs2 // Class Time1 maintains time in 24-hour format.3 4 using System;5 6 // Time1 class definition7 public class Time18 {9 private int hour; // 0-2310 private int minute; // 0-5911 private int second; // 0-5912 13 // Time1 constructor initializes instance variables to 14 // zero to set default time to midnight15 public Time1()16 {17 SetTime( 0, 0, 0 );18 }

19 20 // Set new time value in 24-hour format. Perform validity21 // checks on the data. Set invalid values to zero.22 public void SetTime( 23 int hourValue, int minuteValue, int secondValue )24 {25 hour = ( hourValue >= 0 && hourValue < 24 ) ? 26 hourValue : 0;27 minute = ( minuteValue >= 0 && minuteValue < 60 ) ?28 minuteValue : 0;29 second = ( secondValue >= 0 && secondValue < 60 ) ? 30 secondValue : 0;31 }

Private instance variablesDefault constructor

Method SetTime

Validate arguments

Page 95: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

95

TimeTest1.cs1 // TimeTest1.cs2 // Demonstrating class Time1.3 4 using System;5 using System.Windows.Forms;6 7 // TimeTest1 uses creates and uses a Time1 object8 class TimeTest19 {10 // main entry point for application11 static void Main( string[] args )12 {13 Time1 time = new Time1(); // calls Time1 constructor15 1622 // attempt valid time settings23 time.SetTime( 13, 27, 6 );24 31 // attempt invalid time settings32 time.SetTime( 99, 99, 99 );33

Page 96: Introduction to Microsoft .NET - York University notes/Lecture Notes 3403 week 02… · Introduction to Microsoft .NET ... • Can download ... ASP.NET apps, etc] • Can get a copy

96

Class Scope• All members are accessible within the class’s methods

and can be referenced by name• Instance variables may also be accessed by using the

keyword this and the dot operator (such as this.hour).• Outside a class, private members cannot be referenced

by name, public members may be referenced using the dot operator (referenceName.memberName )

• Method-scope variables– Only accessible within the methods in which they are defined– Hide instance variables


Recommended