Introduction to design patterns in c# james w. cooper pdf
Each and everyone is suffering from some or the other sickness. It is difficult to imagine a world without Framework, but there once was.
In the olden days, it was so difficult doing any sort of image manipulation in Visual Basic. This is where Photoshop has earned my respect. Specifically, the book introduces and explains how to employ a set of reusable software design. Visual Basic is like this: Much like dynamite a lot of good things could be done with it but, because of the baser nature of human beings, a lot of horrible things have been done with it. I have often wondered if Alan Cooper will have his Alfred N.
James W. Cooper has 29 books on Goodreads with ratings. Over stylesheets are included. Multithreading Backup Utility. Multithreading is something we will all have to deal with sooner or later. This relatively simple application shows you how to use two threads to copy files. It is also a very handy Windows backup utility with a mirror feature, a batch mode feature, a log file feature and a help button. In the past, I received a bad comment for I am using an obsolete version of visual basic.
So I made an upgrade with my Hotel Reservation System from VB to Just a note though for VB programmer —kindly continue with what you are doing right now if you feel you are more productive in version.
Last edited by Kajishicage. Share this book. Enhancing Security in the Wastewater Sector. De specierum scrutinio et lampade combinatoria Raymundi Lullii The Learning Process.
Studying Design Patterns. Notes on Object-Oriented Approaches. C Design Patterns. How This Book Is Organized. Syntax of the C Language. Data Types. Converting between Numbers and Strings. Declaring Multiple Variables. Numeric Constants. Character Constants. Declaring Variables as You Use Them. Multiple Equals Signs for Initialization. A Simple C Program. Arithmetic Operators. Increment and Decrement Operators. Combining Arithmetic and Assignment Statements.
Making Decisions in C. Comparison Operators. Combining Conditions. The Most Common Mistake. The Switch Statement. C Comments. The Ornery Ternary Operator. Looping Statements in C. The While Loop. The Do-While Statement. The For Loop. Declaring Variables as Needed in For Loops. Commas in For Loop Statements. How C Differs from C. How C Differs from Java. Writing Windows C Programs.
Objects in C. Managed Languages and Garbage Collection. Classes and Namespaces in C. Building a C Application. The Simplest Window Program in C. Windows Controls. Radio Buttons. ListBoxes and ComboBoxes. The Items Collection. The Windows Controls Program. Using Classes and Objects in C. A Simple Temperature Conversion Program.
Building a Temperature Class. Converting to Kelvin. Putting the Decisions into the Temperature Class. Using Classes for Format and Value Conversion. Handling Unreasonable Values. A String Tokenizer Class. Classes as Objects. Class Containment. Classes and Properties. Programming Style in C. Operator Overloading. Drawing and Graphics in C. Using Inheritance. Creating a Square from a Rectangle. Public, Private, and Protected. Virtual and Override Keywords.
Overriding Methods in Derived Classes. Replacing Methods Using New. Overriding Windows Controls. Abstract Classes. Comparing Interfaces and Abstract Classes. UML Diagrams. C Project Files. Arrays, Files, and Exceptions in C. Collection Objects. Multiple Exceptions. Throwing Exceptions. File Handling. The File Object. Reading a Text File. Writing a Text File. Exceptions in File Handling. Testing for End of File. A csFile Class. The Simple Factory Pattern. How a Simple Factory Works.
Sample Code. The Two Derived Classes. Building the Simple Factory. Using the Factory. Factory Patterns in Math Computation. Thought Questions. The Factory Method.
The Swimmer Class. The Events Classes. Our Seeding Program. Other Factories. When to Use a Factory Method. Thought Question. The Abstract Factory Pattern. A GardenMaker Factory.
The PictureBox. Handling the RadioButton and Button Events. Adding More Classes. Consequences of Abstract Factory. The Singleton Pattern.
Creating Singleton Using a Static Method. Exceptions and Instances. Throwing the Exception. Creating an Instance of the Class. Providing a Global Point of Access to a Singleton. Other Consequences of the Singleton Pattern. The Builder Pattern. An Investment Tracker. As soon as the garbage collection system detects that there are no more active references to a variable, array or object, the memory is released back to the system.
So you no longer need to worry as much about running out of memory because you allocated memory and never released it. Of course, it is still possible to write memory-eating code, but for the most part you do not have to worry about memory allocation and release problems.
Classes and Namespaces in C All C programs are composed entirely of classes. Since everything is a class, the number of names of class objects can get to be pretty overwhelming.
They have therefore been grouped into various functional libraries that you must specifically mention in order to use the functions in these libraries. Under the covers these libraries are each individual DLLs. However, you need only refer to them by their base names using the using statement, and the functions in that library are available to you.
Drawing; using System. Collections; Logically, each of these libraries represents a different namespace. Each namespace is a separate group of class and method names which the compiler will recognize after you declare that name space. You can use namespaces that contain identically named classes or methods, but you will only be notified of a conflict if you try to use a class or method that is duplicated in more than one namespace.
The most common namespace is the System namespace, and it is imported by default without your needing to declare it. It contains many of the most fundamental classes and methods that C uses for access to basic classes such as Application, Array, Console, Exceptions, Objects, and standard objects such as byte, bool, string.
The entry point of any program must be a Main method, and it must be declared as static. Start the Visual Studio. From the selection box, choose C Console application as shown in Figure Selecting a console application. This will bring up a module, with Main already filled in. You can type in the rest of the code as follows: Console.
In fact, you can create most of it using the Windows Designer. To do this, start Visual Studio. The default name and filename is WindowsApplication1, but you can change this before you close the New dialog box.
This brings up a single form project, initially called Form1. You can then use the Toolbox to insert controls, just as you can in Visual Basic. Figure — The Windows designer in Visual Studio.
NET You can draw the controls on the form by selecting the TextBox from the Toolbox and dragging it onto the form, and then doing the same with the button. Then to create program code, we need only double click on the controls. Under the covers, it also connects the event to this method.
The running program is shown in Figure While we only had to write one line of code inside the above subroutine, it is instructive to see how different the rest of the code is for this program. We first see that several libraries of classes are imported so the program can use them: using System; using System. Collections; using System.
ComponentModel; using System. Forms; using System. Data; Most significant is the Windows. Forms library, which is common to all the. Net languages. The code the designer generates for the controls is illuminating. And it is right there in the open for you to change if you want. Essentially, each control is declared as a variable and added to a container.
Here are the control declarations. Note the event handler added to the btHello. Click event. TextBox txHi; private System. Button ; this. Point 80, ; this. Size 64, 24 ; this. Point 64, 48 ; this. Size , 20 ; this. Size 5, 13 ; this. Size , ; this. AddRange new System. Many of the more common ones are shown in the Windows Controls program in Figure Figure — A selection of basic Windows controls. Each of these controls has properties such as Name, Text, Font, Forecolor and Borderstyle that you can change most conveniently using the properties window shown at the right of Figure You can also change these properties in your program code as well.
The Windows Form class that the designer generates always creates a Form1 constructor that calls an InitializeComponent method like the one above. One that method has been called, the rest of the controls have been created and you can change their properties in code.
Generally, we will create a private init method that is called right after the InitializeComponent method, in which we add any such additional initialization code.
Usually programmers use this to label the purpose of text boxes next to them. However, if you want, you can change the major properties in Table either in the designer or at runtime.
If false , grayed out. If true, you can still select the text and copy it, or set values from within code. You can set or interrogate this property in code as well as in the designer. You can create an event handler to catch the event when the box is checked or unchecked, by double clicking on the checkbox in the design mode.
CheckBoxes have a Appearance property which can be set to Appearance. Normal or Appearance. When the appearance is set to the Button value, the control appears acts like a toggle button that stays depressed when you click on it and becomes raised when you click on it again. All the properties in Table apply as well. Buttons A Button is usually used to send a command to a program. When you click on it, it causes an event that you usually catch with an event handler.
Like the CheckBox, you create this event handler by double clicking on the button in the designer. All of the properties in Table can be used as well. Buttons are also frequently shown with images on them.
You can set the button image in the designer or at run time. The images can be in bmp, gif, jpeg or icon files. Radio buttons Radio buttons or option buttons are round buttons that can be selected by clicking on them. Only one of a group of radio buttons can be selected at a time. If there is more than one group of radio buttons on a window form, you should put each set of buttons inside a Group box as we did in the program in Figure Radio buttons do not always have events associated with them.
Instead, programmers check the Checked property of radio buttons when some other event, like an OK button click occurs. Listboxes and Combo Boxes Both list boxes and Combo boxes contain an Items array of the elements in that list. A ComboBox is a single line drop-down, that programmers use to save space when selections are changed less frequently. ListBoxes allow you to ser properties that allow multiple selections, but ComboBoxes do not.
Some of their properties include those in Table If set to MultiSimple, you can select or deselect multiple items with a mouse click. If set to MultiExtended, you can select groups of adjacent items with a mouse. SelectedIndex Index of selected item SelectedIndices Returns collection of selections when list box selection mode is multiple. SelectionMode and MultiColumn do not apply to combo boxes.
It is essentially an ArrayList, as we discuss in Chapter 8. The basic methods are shown in Table SelectedObjectCollection lsCommands ; where lsCommands is the list box name. Menus You add menus to a window by adding a MainMenu controls to the window form. Then, you can the menu control and edit its drop-down names and new main item entries as you see in Figure Figure — Adding a menu to a form. As with other clickable controls, double clicking on one in the designer creates an event whose code you can fill in.
ToolTips A ToolTip is a box that appears when your mouse pointer hovers over a control in a window. In our example in Figure , we add tooltips text to the button and list box using the tips control we have added to the window. SetToolTip btPush, "Press to add text to list box" ; tips. Figure — A ToolTip over a button. Add "8" ; cbFont. Add "10" ; cbFont. Add "12" ; cbFont. Add "14" ; cbFont. Add "18" ; lbText. ToInt16 cbFont. All C programs are composed of classes. The Windows forms we have just seen are classes, derived from the basic Form class and all the other programs we will be writing are made up exclusively of classes.
C does not have the concept of global data modules or shared data that is not part of classes. Simply put, a class is a set of public and private methods and private data grouped inside named logical units. Usually, we write each class in a separate file, although this is not a hard and fast rule.
We have already seen that these Windows forms are classes, and we will see how we can create other useful classes in this chapter. When you create a class, it is not a single entity, but a master you can create copies or instances of, using the new keyword. When we create these instances, we pass some initializing data into the class using its constructor. A constructor is a method that has the same name as the class name, has no return type and can have zero or more parameters that get passed into each instance of the class.
We refer to each of these instances as objects. A Simple Temperature Conversion Program Suppose we wanted to write a visual program to convert temperatures between the Celsius and Fahrenheit temperature scales. You may remember that water freezes at zero on the Celsius scale and boils at degrees, while on the Fahrenheit scale, water freezes at 32 and boils at From these numbers you can quickly deduce the conversion formula that you may have forgotten.
Figure — Converting 35 Celsius to 95 Fahrenheit with our visual interface. Using the visual builder provided in Visual Studio. NET, we can draw the user interface in a few seconds and simply implement routines to be called when the two buttons are pressed. ToSingle txEntry.
ToString ; txEntry. However, it has some disadvantages that we might want to improve on. The most significant problem is that the user interface and the data handling are combined in a single program module, rather than being handled separately. Building a Temperature Class A class in C is a module that can contain both public and private functions and subroutines, and can hold private data values as well.
These functions and subroutines in a class are frequently referred to collectively as methods. Class modules allow you to keep a set of data values in a single named place and fetch those values using get and set functions, which we then refer to as accessor methods. You create a class module from the C integrated development environment IDE using the menu item Project Add class module. When you specify a filename for each new class, the IDE assigns this name as the class name as well and generates an empty class with an empty constructor.
Note that the system generates the class and a blank constructor. If your class needs a constructor with parameters, you can just edit the code. Now, what we want to do is with this class is to move all of the computation and conversion between temperature scales into this new Temperature class. One way to design this class is to rewrite the calling programs that will use the class module first.
Note that we put the string value of the input temperature into the class in the constructor, and that inside the class it gets converted to a float. You can only put data into the class and get it back out using the constructor and the getConvTemp method. The main point to this code rearrangement is that the outer calling program does not have to know how the data are stored and how they are retrieved: that is only known inside the class.
The other important feature of the class is that it actually holds data. You can put data into it and it will return it at any later time. This class only holds the one temperature value, but classes can contain quite complex sets of data values. This is the coldest possible temperature, since it is the point at whic h all molecular motion stops. The Kelvin scale is based on absolute zero, but the degrees are the same size as Celsius degrees.
Putting the Decisions into the Temperature Class Now we are still making decisions within the user interface about which methods of the temperature class. It would be even better if all that complexity could disappear into the Temperature class. Text , opCels. The class that handles all this becomes somewhat more complex, however, but it then keeps track of what data as been passed in and what conversion must be done.
The public ones are callable from other modules, such as the user interface form module. The private ones, getCels and getFahr, are used internally and operate on the temperature variable.
Note that we now also ha ve the opportunity to return the output temperature as either a string or a single floating point value, and could thus vary the output format as needed. Using Classes for Format and Value Conversion It is convenient in many cases to have a method for converting between formats and representations of data. You can use a class to handle and hide the details of such conversions. For example, you might design a program where you can enter an elapsed time in minutes and seconds with or without the colon: Figure — A simple parsing program that uses the Times class.
Much of the parsing work takes place in the constructor for the class. Parsing depends primarily on looking for a colon.
If there is no colon, then values greater than 99 are treated as minutes. ToInt32 entry. ToSingle entry. Depending on the kind of time measurements these represent, you might also have some non-numeric entries such as NT for no time or in the case of athletic times, SC for scratch or DQ for disqualified. All of these are best managed inside the class.
Thus, you never need to know what numeric representations of these values are used internally. Handling Unreasonable Values A class is also a good place to encapsulate error handling. For example, it might be that times greater than some threshold value are unlikely and might actually be times that were entered without a decimal point. If large times are unlikely, then a number such as could be assumed to be You can also use the class constructor to set up default values for variables.
While C does not exactly provide a class for this feature, we can write one quite easily us ing the Split method of the string class. The goal of the Tokenizer class will be to pass in a string and obtain the successive string tokens back one at a time.
We use the Split function, which approximates the Tokenizer but returns an array of substrings instead of having an object interface. The class we want to write will have a nextToken method that returns string tokens or a zero length string when we reach the end of the series of tokens. The whole class is shown below. Split delimiter. Figure — The tokenizer in use. Text ; while tok. Add tok. A class is just a module as we have shown above, which has both public and private methods and which can contain data.
We frequently refer to these instances as objects. Suppose as have a file of results from a swimming event stored in a text data file. An efficient way to keep the data for each swimmer grouped together is to design a Swimmer class and create an instance for each swimmer. Here is how we read the file and create these instances. Add swm. ToInt32 tok. Having a class contain other classes is a very common ploy in OO programming and is one of the main ways we can build up more complicated programs from rather simple components.
The program that displays these swimmers is shown in Figure When you click on any swimmer, her time is shown in the box on the right. These correspond to the kinds of properties you associate with Forms, but they can store and fetch any kinds of values you care to use. To use these properties, you refer to the age property on the left side of an equals sign to set the value, and refer to the age property on the right side to get the value back.
They do not provide any features not already available using get and set methods and both generate equally efficient code. In the revised version of our SwimmerTimes display program, we convert all of the get and set methods to properties, and then allow users to vary the times of each swimmer by typing in new ones.
We favor using names for C controls such as buttons and list boxes that have prefixes that make their purpose clear, and will use them whenever there is more than one of them on a single form: Control name Prefix Example Buttons bt btCompute List boxes ls lsSwimmers Radio option buttons op opFSex Combo boxes cb cbCountry Menus mnu mnuFile Text boxes tx txTime We will not generally create new names for labels, frames and forms when they are never referred to directly in the code.
We will begin class names with capital letters and instances of classes with lowercase letters. Each class can have many instances and each could contain different data values. Classes can also have Property methods for setting and fetching data. These Property methods provide a simpler syntax over the usual getXXX and setXX accessor methods but have no other substantial advantages.
NET : inheritance. Form This says that the form we create is a child class of the Form class, rather than being an instance of it.
This has some very powerful implications. You can create visual objects and override some of their properties so that each behaves a little differently. Constructors All classes have specific constructors that are called when you create an instance of a class. These constructors always have the same name as the class. This applies to form classes as well as non- visual classes.
If you do not specifically include a constructor in any class you write, a constructor having no arguments is generated for you under the covers. The InitializeComponent method is generated by the IDE as well, and contains code that creates and positions all the visual controls in that window. In C , controls are repainted by the Windows system and you can connect to the paint event to do your own drawing whenever a paint event occurs.
Such a paint event occurs whenever the window is resize, uncovered or refreshed. This brings up a list of all the events that can occur on a PictureBox as shown in Figure To do drawing, you must create an instance of a Pen object and define its color and, optionally its width.
This is illustrated below for a black pen with a default width of 1. Using Inheritance Inheritance in C gives us the ability to create classes which are derived from existing classes. In new derived classes, we only have to specify the methods that are new or changed.
All the others are provided automatically from the base class we inherit from. To see how this works, lets consider writing a simple Rectangle class that draws itself on a form window.
This class has only two methods, the constructor and the draw method. Visual Studio. Net also creates a namespace for each project equal to the name of the project itself. You can change this namespace on the property page, or make it blank so that the project is not in a namespace. However, you can create namespaces of your own, and the Rectangle class provides a good example of a reason for doing so. The System. Drawing namespace that this program requires to use the Graphics object also contains a Rectangle class.
Then, when we declare the variable in the main Form window, we can declare it as a member of that namespace. Rectangle rec; In this main Form window, we create an instance of our Rectangle class. Graphics; rect.
Creating a Square From a Rectangle A square is just a special case of a rectangle, and we can derive a square class from the rectangle class without writing much new code. The Rectangle class creates the pen and does the actual drawing. Note that there is no draw method at all for the Square class.
Public, Private and Protected In C , you can declare both variables and class methods as public, private or protected. A public method is accessible from other classes and a private method is accessible only inside that class.
Usually, you make all class variables private and write getXxx and seXxx accessor functions to set or obtain their values. It is generally a bad idea to allow variables inside a class to be accessed directly from outside the class, since this violates the principle of encapsulation.
In other words, the class is the only place where the actual data representation should be known, and you should be able to change the algorithms inside a class without anyone outside the class being any the wiser.
C introduces the protected keyword as well. Both variables and methods can be protected. Protected variables can be accessed within the class and from any subclasses you derive from it.
Similarly, protected methods are only accessible from that class and its derived classes. If you do not declare any level of accessibility, private accessibility is assumed. Overloading In C as well as other object oriented languages, you can have several class methods with the same name as long as they have different calling arguments or signatures. For example we might want to create an instance of a StringTokenizer class where we define both the string and the separator.
Here are the two constructors. Virtual and Override Keywords If you have a method in a base class that you want to allow derived classes to override, you must declare it as virtual. This means that a method of the same name and argument signature in a derived class will be called rather than the one in the base class. Then, you must declare the method in the derived class using the override keyword.
If you create a method in a derived class that is identical in name and argument signature to one in the base class and do not declare it as overload, this also is an error.
Overriding Methods in Derived Classes Suppose we want to derive a new class called DoubleRect from Rectangle, which draws a rectangle in two colors offset by a few pixels. We could keep our own copy of these parameters in the DoubleRect class, or we could change the protection mode of these variables in the base Rectangle class to protected from private.
Figure - The DoubleRect classes. Replacing Methods Using New Another way to replace a method in a base class when you cannot declare the base class method as virtual is to use the new keyword in declaring the method in the derived class. If you do this, it effectively hides any methods of that name regardless of signature in the base class.
In that case, you cannot make calls to the base method of that name from the derived class, and must put all the code in the replacement method. DrawRectangle rpen, x, y, w, h ; g. In C , we can create that new control by just deriving a new class from the Textbox class. The new HiTextBox control will appear at the bottom of the Toolbox on the left of the development environment. You can create visual instances of the HtextBox on any windows form you create.
This is shown in Figure Figure -The Toolbox, showing the new control we created and an instance of the HiTextBox on the Windows Designer pane of a new form.
Now we can modify this class and insert the code to do the highlighting. We have derived a new Windows control in about 10 lines of code. You can see the resulting program in Figure Figure If you run this program, you might at first think that the ordinary TextBox and the HiTextBox behave the same, because tabbing between them makes them both highlight. However, if you click inside the Textbox and the HiTextBox and tab back and forth, you will see in Figure that only our derived HiTextBox continues to highlight.
Interfaces An interface is a declaration that a class will contain a specific set of methods with specific arguments. If a class has those methods, it is said to implement that interface.
It is essentially a contract or promise that a class will contain all the methods described by that interface. Interfaces declare the signatures of public methods, but do not contain method bodies.
If a class implements an interface called Xyz, you can refer to that class as if it was of type Xyz as well as by its own type. Since C only allows a single tree of inheritance, this is the only way for a class to be a member of two or more base classes.
Abstract Classes An abstract class declares one or more methods but leaves them unimplemented. If you declare a method as abstract, you must also declare the class as abstract.
Suppose, for example, that we define a base class called Shape. It will save some parameters and create a Pen object to draw with. We also declare the overall class as abstract. You can only create instances of derived classes in which the abstract methods are filled in. It has a real draw method. Note that since they are both of base type Shape we can treat them as Shape objects: public class Form1 : System. Graphics ; rect. There is no default method code generated: you must include it yourself.
If you leave an interface method out of a class that is supposed to implement that interface, the compiler will generate an error. When you create an abstract class, you are creating a base class that might have one or more complete, working methods, but at least one that is left unimplemented, and declared abstract.
The purpose of abstract classes is to provide a base class definition for how a set of derived classes will work, and then allow the programmer to fill these implementations in differently in the various derived classes. Another related approach is to create base classes with empty methods. These guarantee that all the derived classes will compile, but that the default action for each event is to do nothing at all. And there will be no hint what method you are supposed to override, as you would get from using an abstract class.
C provides inheritance, constructors and the ability to overload methods to provide alternate versions. This leads to the ability to create new derived versions even of Windows controls.
This simple diagramming style was developed from work done by Grady Booch, James Rumbaugh, and Ivar Jacobson, which resulted in a merging of ideas into a single specification and, eventually, a standard. You can read details of how to use UML in any number of books such as those by Booch et al. Basic UML diagrams consist of boxes representing classes. Static methods are shown underlined. You can also show all of the type information in a UML diagram where that is helpful, as illustrated in Figure a.
For example, in Figure b, we have omitted some of the method details. We will also make the getJob method abstract in the base Person class, which means we indicate it with the MustOverride keyword. While it has been conventional to show the inheritance with the arrow pointing up to the superclass, UML does not require this, and sometimes a different layout is clearer or uses space more efficiently. Interfaces An interface looks much like inheritance, except that the arrow has a dotted line tail, as shown in Figure Figure — ExitCommand implements the Command interface.
Composition Much of the time, a useful representation of a class hierarchy must include how objects are contained in other objects. For example, a small company might include one Employee and one Person perhaps a contractor.
Figure — Company contains instances of Person and Employee. The lines between classes show that there can be 0 to 1 instances of Person in Company and 0 to 1 instances of Employee in Company. The diamonds indicate the aggregation of classes within Company. Some writers have used hollow and solid diamond arrowheads to indicate containment of aggregates and circle arrowhead for single object composition, but this is not required.
Annotation You will also find it convenient to annotate your UML or insert comments to explain which class calls a method in which other class. You can place a comment anywhere you want in a UML diagram. Comments may be enclosed in a box with a turned corner or just entered as text. Text comments are usually shown along an arrow line, indicating the nature of the method that is called, as shown in Figure UML is quite a powerful way of representing object relationships in programs, and there are more diagram features in the full specification.
However, the preceding brief discussion covers the markup methods we use in this text. This program reads in the actual compiled classes and generates the UML class diagrams we show here. We have edited many of these class diagrams to show only the most important methods and relationships. Thus, you can run your demo copy of WithClass on the enclosed CD and read in and investigate the detailed UML diagram starting with the same drawings you see here in the book.
Each subdirectory of the CD-ROM contains the project file for that project so you can load the project and compile it as we did. Arrays, Files and Exceptions in C C makes handling arrays and files extremely easy and introduces exceptions to simplify error handling.
Arrays In C , all arrays are zero based. Collections namespace contains a number of useful variable length array objects you can use to add and obtain items in several ways. ArrayLists The ArrayList object is essentially a variable length array that you can add items to as needed. IndexOf object Returns the first index of the value Insert index, object Insert the element at the specified index. Remove object Remove element from list. Typically, keys are strings of some sort, but they can be any sort of object.
Each element must have a unique key, although the elements themselves need not be unique. Hashtables are used to allow rapid access to one of a large and unsorted set of entries, and can also be used by reversing the key and the entry values to create a list where each entry is guaranteed to be unique.
Hashtables also have a count property and you can obtain an enumeration of the keys or of the values. SortedLists The SortedList class maintains two internal arrays, so you can obtain the elements either by zero-based index or by alphabetic key. Add "fred", freddy ; slist. Exceptions Error handling in C is accomplished using exceptions instead of other more awkward kinds of error checking.
The thrust of exception handling is that you enclose the statements that could cause errors in a try block and then catch any errors using a catch statement. The way this works is that the statements in the try block are executed and if there is no error, control passes to the finally statements if any, and then on out of the block.
If errors occur, control passes to the catch statement, where you can handle the errors, and then control passes on to the finally statements and then on out of the block. The following example shows testing for any exception. WriteLine e. Must be non-negative and less than the size of the collection. Parameter name: index at System.
Some of the more common exceptions are shown in Table AccessException Error in accessing a method or field of a class. Multiple Exceptions You can also catch a series of exceptions and handle them differently in a series of catch blocks.
0コメント