Object-oriented Programming In C#

3y ago
73 Views
9 Downloads
2.90 MB
485 Pages
Last View : 20d ago
Last Download : 3m ago
Upload by : Emanuel Batten
Transcription

Object-orientedProgramming in C#for C and Java programmersFebruary 2010Kurt Nørmark Department of Computer Science,Aalborg University,Denmark.WEB version:http://www.cs.aau.dk/ normark/oop-csharp/html/notes/theme-index.html

ii

AbstractThis is a teaching material about object-oriented programming, illustrated with use of theprogramming language C#. The initial version was written i 2006.It is assumed, as a prerequisite, that the readers have some knowledge about imperativeprogramming, preferably knowledge about C. I believe that it is best to learn object-orientedprogramming after having learned and worked with imperative programming. Thus, weadhere to an "object later approach".The starting point of of this teaching material is a number of slides. The slides are annotatedwith explanations and additional resources. The most comprehensive version of the materialhas the form of a traditional textbook. You can think of the textbook as grown on top of theslide material.Almost all programs in this material have been developed together with the material.However, a few programs come from other sources. If the programs are not original, thesource programmers are mentioned and acknowledged in an initial comment line of theprogram.The current version of the material is complete up to (and including) the last chapter inlecture about Contracts (chapter 53). The final chapters - corresponding to the lectures abouttest and documentation - only contain slide material.The teaching material is an online material represented in HTML. A PDF version of thetextbook is also available. In order to limit the size of the PDF files some less importantprograms have been left out from the PDF edition. In the web edition (in HTML files) thefull content is available.We have used colors to emphasize aspects of the source programs in this material. It istherefore recommeded that you read the material from a color medium.We would like to point out a couple of qualities of the web edition of the material. First, wehave provided for extensive cross linking of the material. Whenever relevant, we haveprovided links from one part of the material to another. We have also provided acomprehensive subject index. Finally, there are separate indexes of source programs andexercises. The source program index provides links to complete, textual versions of the C#programs of the material, ready for you to compile and use.In the spring of 2008 the material has been used in a course where the students have abackground in imperative Visual Basic programming. We have therefore added a chapterthat compares the fundamental (non-objected) parts of Visual Basic with the similar parts ofC#. The chapter about Visual Basic is only available in the web-version.Prior to the fall semester of 2008, selected aspects of C# 3.0 have been included in thematerial. This includes automatic properties, object initializers, extension methods, andlambda expressions.iii

The January 2009 edition includes a number of bug-fixes (as collected during the fall of2008) and some new exercises targeted at the Aalborg University OOPA spring course 2009at the BAIT education.The February 2010 edition is a minor revision compared with the August 2009 edition. TheFebruary 2010 edition is the last, and final, version of the teaching material.Kurt Nørmarknormark@cs.aau.dkDepartment of Computer ScienceAlborg UniversityDenmarkFebruary 5, 2010Colophon: This material has been made with the LENO system. LENO is an XML language which isdefined by an XML DTD. LENO is used together with LAML. LAML is a software package that makesXML available in the Scheme programming language. For this version of the material, LAML version 35.0(development version) has been used. This setup allows us to write LENO material in the programminglanguage Scheme. Thus, the source of this material has been written in Scheme with use of the mirrorfunctions of LENO XML language. Most illustrations have been written in an extension of SVG whichallows for high-level representations of graphs. Batik 1.6 has been used to rasterize the SVG images in someversions of the material. The primary target format of the teaching material is HTML. LENO can be used toproduce different views of the material. In the concrete material we make use of the slide view and thethematic view (the text book view). The aggregated slide view is also available. The PDF version of thethematic view (the text book view) has been made by PDF Creator (version 0.9.5 ). Text breaking and pageenumeration has been made in Microsoft Word 2003 via 'Edit with Microsoft Word' in Internet Explorerversion 7.0.iv

Contents1.2.3.4.From structured programming to object-oriented programmingTowards Object-oriented ProgrammingPhenomena and ConceptsTowards Object-oriented Programs1713195.6.7.8.9.The C# Language and SystemC# in relation to CC# in relation to JavaC# in relation to Visual BasicC# Tools and IDEs232553575910. Classes: An Initial Example11. Classes12. Creating and Deleting Objects61678913.14.15.16.Reference TypesValue TypesOrganization of C# ProgramsPatterns and Techniques9710311712317.18.19.20.Accessing Data in 23.24.Overloaded OperatorsDelegatesEventsPatterns and Techniques16517318318925.26.27.28.Specialization of ClassesExtension of ClassesInheritance in GeneralInheritance in C#195203209215v

29.30.31.32.Method CombinationAbstract Classes - Sealed ClassesInterfacesPatterns and Techniques24124525327133.34.35.36.Fundamental Questions about Exception HandlingConventional Exception HandlingObject-oriented Exception HandlingExceptions and Exception Handling in C#30130731131337.38.39.40.StreamsDirectories and FilesSerializationPatterns and Techniques33335535936941. Motivation for Generic Types42. Generic Types43. Generic Methods37338140144.45.46.47.48.Collections - History and OverviewGeneric Collections in C#Generic Dictionaries in C#Non-generic Collections in C#Patterns and ecification with preconditions and postconditionsResponsibilities and ContractsClass Invariants453457463471vi

1. From structured programming to object-orientedprogrammingWe will assume that the reader of this material has some knowledge of imperative programming, and that thereader already has been exposed to the ideas of structured programming. More specifically, we will assumethat the reader has some background in C programming. In Chapter 6 (corresponding to the second lecture ofthe course) we summarize the relationships between C and C#.1.1. Structured ProgrammingLecture 1 - slide 2We approach object-oriented programming by reviewing the dominating programming approach prior toobject-oriented programming. It is called structured programming. A brief background on structuredprogramming, imperative programming, and - more generally - different schools of programming is providedin Focus box 1.1. I will recommend that you read the Wikipedia article about structured programming [wikistr-pro]. It captures, very nicely, the essence of the ideas.Structured programming relies on use of high-level control structures instead of low-leveljumpingStructured programming is also loosely coupled with top-down programming and programdevelopment by stepwise refinementStructured programming covers several, loosely coupled ideas. As summarized above, one of these is the useof control structures (such as if, switch/case, while and for) instead of gotos.Use of relatively small procedures is another idea. A well-structured program should devote a singleprocedure to the solution of a single problem. The splitting of problems in subproblems should be reflectedby breaking down a single procedure into a number of procedures. The idea of program development bystepwise refinement [Wirth71] advocates that this is done in a top-down fashion. The items below summarizethe way it is done. Start by writing the main program Use selective and iterative control structures Postulate and call procedures P1, .,PnImplement P1, . Pn, and in turn the procedures they make use ofEventually, the procedures become so simple that they can be implemented without introducingadditional proceduresOnly few programmers are radical with respect to top-down structured programming. In the practical worldit is probably much more typical to start somewhere in the middle, and then both work towards the top andtowards the bottom.1

Imperative programming, Structured programming, and Programmingparadigms.FOCUS BOX1.1Imperative programming is one of the four main programming paradigms. The others are functionalprogramming, object-oriented programming, and logic programming.Imperative programming is closely related to the way low-level machine languages work: Commands areused to change the values of locations in the memory of the computer. In high-level languages, this isachieved by use of assignment statements, which is used to change the values of variables. The assignmentstatement is therefore the archetypical command in imperative programming. Control structures (sequence,selection, and iteration) come on top of that together with procedural abstractions.Programming done in the early years of the computing era (before the introduction of Algol) is often thoughtof as "unstructured programming". Unstructured programming is largely characterized by use of "jumpingaround" by means of goto commands. The introduction of if and while control structures together withprocedures eliminated the need for gotos. This can be shown theoretically, but - more important - it alsoholds true in the practical world of imperative programming. Armed with the common control structures (ifand while, for instance) and procedural abstraction, very few programmers are tempted to use a gotostatement in the programs they write. Such programming, without use of goto statements, is often calledstructured programming.1.2. A structured program: HangmanLecture 1 - slide 3In order to be concrete we will look at parts of a C program. The program implements a simple andrudimentary version of the well-known Hangman game. We will pretend that the program has beendeveloped according to the structured programming ideas described in Section 1.1.The main Hangman program, main, is shown in Program 1.1. The fragments shown in purple are postulated(in the sense discussed in Section 1.1). I.e., they are called, but not yet defined at the calling time. Thepostulated procedures are meant to be defined later in the program development process. Some of them areshown below.1 int main(void){2char *playerName;answer again;34playerName ayerName);8again askUser("Do you want to play again");910} while (again yes);11 }Program 1.1program.The main function of the HangmanThe function getPlayerName is intended to prompt the Hangman player for his or her name. As it appears inProgram 1.2 this function only uses functions from the C standard library. Therefore there are no emphasizedparts in getPlayerName.2

1 char *getPlayerName(){2char *playerName (char*)malloc(NAME MAX);34printf("What is your name? ");5fgets(playerName, NAME MAX, stdin);6playerName[strlen(playerName)-1] '\0';7return playerName;8 }Program 1.2The function getPlayerName of main.The function initHangman calls an additional initialization function called initPuzzles, which reads apuzzle from a text file. We will here assume that this function does not give rise to additional refinement. Wedo not show the implementation of initPuzzles.1 void initHangman ");34 }Program 1.3The function initHangman of main.is a general purpose function, which was called in main in Program 1.1. We show it in Program 1.4(only on web) and we see that it does not rely on additional functions.askUserThe function playHangman, seen in Program 1.5, is called by main in the outer loop in Program 1.1.playHangman contains an inner loop which is related to a single round of playing. As it appears fromProgram 1.5 playHangman calls a lot of additional functions (all emphasized, but not all of them includedhere).1 void playHangman (char playerName[]){2int aPuzzleNumber, wonGame;puzzle secretPuzzle;3hangmanGameState gameState;45char playersGuess;6initGame(playerName, &gameState);78aPuzzleNumber rand() % numberOfPuzzles();secretPuzzle getPuzzle(aPuzzleNumber);91011while ((gameState.numberOfWrongGuesses N) &&12(gameState.numberOfCorrectGuesses (gameState, gameState); ; printf("\n");15if (CHEATING) ;playersGuess gameState, secretPuzzle, playersGuess);2021}gameStatistics(gameState, secretPuzzle);22wonGame e(gameState, secretPuzzle, wonGame);2425 }Program 1.5The function playHangman of main.3

In Program 1.6 (only on web) and Program 1.7 (only on web), we show two additional functions, initGameand getPuzzle, both of which are called in playHangman in Program 1.5.As already brought up in Section 1.1 many programmers do not strictly adhere to structured programmingand top-down refinement when coding the hangman program. If you have programmed Hangman, or asimilar game, it is an interesting exercise to reflect a little on the actual approach that was taken during yourown development. In Section 4.1 we return to the Hangman example, restructured as an object-orientedprogram.Exercise 1.1. How did you program the Hangman game?This is an exercise for students who have a practical experience with the development of the Hangmanprogram, or a similar game.Recall how you carried out the development of the program.To which degree did you adhere to top-down development by st

1. From structured programming to object-oriented programming 1 2. Towards Object-oriented Programming 7 3. Phenomena and Concepts 13 4. Towards Object-oriented Programs 19 5. The C# Language and System 23 6. C# in relation to C 25 7. C# in relation to Java 53 8. C# in relation to Visual Basic 57 9. C# Tools and IDEs 59 10.

Related Documents:

method dispatch in different object-oriented programming languages. We also include an appendix on object-oriented programming languages, in which we consider the distinction between object-based and object-oriented programming languages and the evolution and notation and process of object-oriented analysis and design, start with Chapters 5 and 6;

object-oriented programming language is based on a kind of old object-oriented programming language. For example, though C language is an object-oriented programming language, it still retains the pointer which is complex but has strong function. But C# improved this problem. C# is a kind of pure object-oriented language.

It stands for Object Oriented Programming. Object‐Oriented Programming ﴾223﴿ uses a different set of programming languages than old procedural programming languages ﴾& 3DVFDO, etc.﴿. Everything in 223 is grouped as self sustainable "REMHFWV". Hence, you gain reusability by means of four main object‐oriented programming concepts.

The principle of object oriented programming is to combine both data and the associated functions into a single unit called a class. An object in programming means data. Data is therefore predominant in object oriented programming. The concept will become clear with examples. However, in the object oriented paradigm, accessibility of

Object Oriented Programming 7 Purpose of the CoursePurpose of the Course To introduce several programming paradigms including Object-Oriented Programming, Generic Programming, Design Patterns To show how to use these programming schemes with the C programming language to build “good” programs.

Object Class: Independent Protection Layer Object: Safety Instrumented Function SIF-101 Compressor S/D Object: SIF-129 Tower feed S/D Event Data Diagnostics Bypasses Failures Incidences Activations Object Oriented - Functional Safety Object: PSV-134 Tower Object: LT-101 Object Class: Device Object: XS-145 Object: XV-137 Object: PSV-134 Object .

Abstract—OOP (Object Oriented Programming) is an object-oriented programming method. The purpose of OOP is to facilitate the development of the program by following the models that have existed in everyday life. Object-oriented programming techniques are becoming very popular today in the process of creating multi-operating system applications.

banking can support a just transition towards a net-zero-carbon economy and society across the regions of the UK. The project is a process of research and collaborative dialogue between stakeholders, including banks and other financial institutions, to help achieve this goal. It has a strong focus on place, taking a regional look first at Yorkshire and the Humber. The project is led by the .