5 Delegates and Events

Size: px
Start display at page:

Download "5 Delegates and Events"

Transcription

1 CH05.qxd 11/14/03 1:08 PM Page Delegates and Events 5.0. Introduction Behavior largely consists of responding to events. Something occurs, and it is our investigation and response to that event that determines what to do next. For instance, when we re assembling some new toy for the kids and a piece breaks, we adjust our behavior accordingly to respond to that event, whether it is to fix it or find some other mechanism to get the job done.with the advent of graphical user interfaces, event-driven programming added a layer on top of procedural programming.that s not saying that procedural programming was entirely replaced because some of its characteristics are in place today. Event-driven programming modifies the behavior of a program due to some internal or external change in state that requires special processing to handle that event. This chapter looks at how events and their supporting constructs, delegates, work within the.net Framework. Initially, you ll learn how to define and use delegates to lay the groundwork necessary to understand how events and event receivers work.you ll also see how you can propagate events to multiple receivers by using multicast delegates Defining and Using Delegates Youwant to define a delegate and allow the use of that delegate within a member function. Technique A delegate is similar to a member method but does not contain a method body. Define a member method using the delegate keyword following the access modifier. Because there is no body associated with the delegate, place a semicolon instead of braces at the end of the method header. For member methods that will use an instance of that delegate, add a

2 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events parameter whose data type is the name of the delegate method name followed by a parameter identifier: class StringPrinterDelegate public delegate void PrintString( string s ); // delegate passed as parameter public static void PrintWithDelegate( PrintString psdelegate, string s ) psdelegate( s ); // internal delegate implementation public static void InternalImp( string s ) Console.WriteLine( s ); To use a delegate within a client application, create an instance of the delegate method whose data type consists of the name of the class, the dot (.) operator, and the name of the delegate.the constructor expects the name of the function that implements this delegate as a parameter.you can locate this delegate implementation within the class that implements the delegate or within a different class, as shown in the code example via the InternalImp method, as long as the method header is identical. Listing 5.1 shows how to create a client application that instantiates two instances of the delegate shown earlier. Each delegate uses a different method implementation using either the static method in the same class as the delegate or the method within the client application class itself. Additionally, the listing also shows how to pass a delegate instance to a method.the output of Listing 5.1 appears in Figure 5.1. Listing 5.1 using System; Defining Delegates namespace _1_Delegates class Class1 [STAThread] static void Main(string[] args) // instantiate delegates StringPrinterDelegate.PrintString internalprint = new StringPrinterDelegate.PrintString ( StringPrinterDelegate.InternalImp );

3 CH05.qxd 11/14/03 1:08 PM Page 137 Chapter 5 Delegates and Events 137 Listing 5.1 Continued StringPrinterDelegate.PrintString firstcharprint = new StringPrinterDelegate.PrintString( FirstCharPrint ); // get string from user Console.Write( Enter a string: ); string input = Console.ReadLine(); // call delegates directly internalprint( input ); firstcharprint( input ); // pass delegates as parameter StringPrinterDelegate.PrintWithDelegate( internalprint, input ); StringPrinterDelegate.PrintWithDelegate( firstcharprint, input ); // external delegate implementation static void FirstCharPrint( string s ) string[] splitstrings = s.split( new char[] ); foreach( string splitstring in splitstrings ) Console.Write( 0, splitstring[0] ); for( int i = 0; i < splitstring.length; i++ ) Console.Write( ); Console.WriteLine(); Comments To delegate means to transfer the care or management of something to a different person or other object. A delegate within the.net Framework acts like a method whose implementation is provided or delegated to some other object. In other words, an object declares that it supports a certain method but relies on different objects or methods to provide the actual implementation. Looking at the syntax of a delegate, it s perfectly reasonable to assume that a delegate is a method because it resides in an object and it is declared much like other methods. However, a delegate is actually converted to a class when the source is compiled to (MSIL).This class name is the name you give to the delegate when you declare it, and the class itself is derived from System.MulticastDelegate, as shown in Figure 5.2,

4 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events which shows the code listing earlier in the ILDasm tool. In the client application shown earlier, you can see that you use the new keyword on a delegate. Because a delegate is in actuality a class, the new keyword is creating an instance of that class. Figure 5.1 Delegates can be associated with different implementations, and you can define those implementations in different classes. Figure 5.2 A delegate is actually a class nested within its containing class. Delegates have been compared to function pointers, and in some cases they are quite similar.the pointer in the delegate sense of the word is a managed pointer to the method, which provides the implementation for the delegate. Because this pointer is managed by the Common Language Runtime (CLR), it is secure, type safe, and verifiable, unlike its

5 CH05.qxd 11/14/03 1:08 PM Page 139 Chapter 5 Delegates and Events 139 unmanaged counterpart.this pointer is passed into the constructor of the delegate when you use the new keyword. If you look at the intermediate language (IL) that is generated when an instance of a delegate is created, you see the instruction ldftn, which places a managed function pointer onto the runtime stack. So the question is now, how does the delegate class that is created call the method using the unmanaged pointer? Looking at the delegate class in ILDasm, you can also see three methods within the class.the first two, BeginInvoke and EndInvoke,are used for asynchronous delegates, which are explained later in this chapter.the third method, Invoke, is where the implementation of the delegate is called. However, double-clicking on the method name in ILDasm shows the method signature with an empty body, as shown in Figure 5.3.When you see this sort of behavior, you will also usually see the attribute runtime managed on the method.when Invoke is called, the CLR retrieves the function pointer that was placed on the runtime stack (with the IL instruction ldftn mentioned earlier), and that is now a member variable within the delegate class, and uses it to call the actual method. The reason no IL shows up in the method is that the act of calling the actual delegate implementation happens within unmanaged code contained within the runtime. Figure 5.3 A delegate s Invoke method is runtime managed. To summarize the steps involved when the CLR creates a delegate, the first step is to convert the delegate into a class derived from System.MulticastDelegate during the compilation process. A client then creates an instance of that class passing a method, either static or nonstatic, to the constructor of that object.this step results in the IL instruction ldftn, which places a managed pointer to the method onto the stack.the delegate constructor places that managed pointer into a member variable within the del-

6 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events egate class.when the actual method is called, the runtime-managed Invoke method is called instead, and unmanaged code within the runtime finds the correct method, via the managed method pointer, and calls its implementation Combining Delegates to Form Multicast Delegates Youwant to use a single delegate but allow it to bind to multiple methods. Technique The generated delegate class is derived from System.MulticastDelegate, which means you are free to use any methods defined in that class for your delegate.to bind to multiple implementations, use the static method Combine, either passing an array of instantiated delegates bound to methods or passing two delegates you want to bind together to create a new delegate: static void Main(string[] args) // create delegate array StringPrinterDelegate.PrintString[] printdelegates = new StringPrinterDelegate.PrintString[3]; // main delegate StringPrinterDelegate.PrintString stringprinters; // create 3 delegates with 3 different implementations printdelegates[0] = new StringPrinterDelegate.PrintString( NormalPrint ); printdelegates[1] = new StringPrinterDelegate.PrintString( FirstCharPrint ); printdelegates[2] = new StringPrinterDelegate.PrintString( LastCharPrint ); // combine the 3 delegates into the main delegate stringprinters = (StringPrinterDelegate.PrintString) Delegate.Combine( printdelegates ); // get string from user Console.Write( Enter a string: ); string input = Console.ReadLine(); // print with main delegate which causes all 3 to be invoked StringPrinterDelegate.PrintWithDelegate( stringprinters, input );

7 CH05.qxd 11/14/03 1:08 PM Page 141 Chapter 5 Delegates and Events 141 Comments Sometimes, you might want a single delegate to bind to several different implementations, thereby causing each implementation to be invoked when the delegate is called. This premise is behind the multicast delegate. A multicast delegate allows you to create several delegate implementations and bind them to only one delegate.therefore, when the delegate is called, each method within the delegate s invocation list is called one after the other. In the code listing earlier, you can see a collection of PrintString delegates being created and placed into an array. Each of them are bound to a certain delegate implementation whose purpose is to simply print a string in a certain way. Once the collection is created, the static method Combine in the System.Delegate class is called, passing the collection as the only parameter.this method enumerates the entire collection and creates a multicast delegate. Because the generated delegate class derives from System.MulticastDelegate,you can assign a variable of that type from the result of the Combine method. However, because Combine returns a generic multicast delegate object, you have to cast the return value to the type you declared. Now any time the multicast delegate is called, each method that it is bound to is called.the PrintWithDelegate method is the same method shown in the previous recipe. No special programming is needed because the Invoke method that is generated for the delegate class will enumerate each method. One thing to keep in mind when creating multicast delegates is order. Unless you are calling a delegate asynchronously, which is discussed in a later recipe, order can be important.the order of method invocations on a multicast delegate is determined based on the order in which the method implementations were bound to it. For the example earlier, the first method invoked is the lowest indexed method within the collection used to create the multicast delegate Removing Individual Delegates from Multicast Delegates You want to remove an individual delegate from the invocation list of a multicast delegate. Technique Use the subtraction assignment operator to remove a delegate that appears at any point within the invocation list of a multicast delegate.you can use the same object that you used to add the delegate and allow the delegate class to find the corresponding delegate within the multicast delegate: StringPrinterDelegate.PrintString[] printdelegates = new StringPrinterDelegate.PrintString[3]; StringPrinterDelegate.PrintString stringprinters;

8 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events printdelegates[0] = new StringPrinterDelegate.PrintString( NormalPrint ); printdelegates[1] = new StringPrinterDelegate.PrintString( FirstCharPrint ); printdelegates[2] = new StringPrinterDelegate.PrintString( LastCharPrint ); stringprinters = (StringPrinterDelegate.PrintString) Delegate.Combine( printdelegates ); // remove index 1 from invocation list stringprinters -= printdelegates[1]; You can also access the invocation list directly and use an individual delegate with the subtraction assignment operator to remove the delegate: Delegate[] delegatelist = stringprinters.getinvocationlist(); stringprinters -= (StringPrinterDelegate.PrintString) delegatelist[delegatelist.length-1]; To remove a range of delegates, you must use another multicast delegate whose invocation list contains the delegates you want to remove.when you use the static Remove method defined in System.Delegate,you remove the last occurrence of a list of delegates within a source multicast delegate.the list of delegates to remove is contained within the second parameter to the function: Delegate.Remove( delegatesource, delegatelist ); If you, however, want to remove all occurrences of an invocation list from a multicast delegate, you can use the RemoveAll static method.whereas the Remove function only removes the last occurrence of an invocation list, RemoveAll removes any and all occurrences of that list within a multicast delegate.the parameters of this method are the same as those for the Remove method. Comments As in physics where every action has an equal and opposite reaction, every addition should have an equal and opposite subtraction within an API. In the recipes leading up to this one, you looked at different ways to add delegates to form multicast delegates.this recipe takes the opposite approach and shows you how to remove individual delegates. The process of removing delegates is essentially the same but, of course, uses different operator and method names.the easiest way to remove a delegate from a multicast delegate is to use the subtraction assignment operator. If the variables that were used to create the initial delegate objects are still within scope, you can use those as the operands to the subtraction assignment operator.when you do so, the delegate class uses object equality methods to find the correct delegate within its invocation list and remove that delegate. If however those variables are no longer in scope, you can still remove them by accessing the invocation list directly via the GetInvocationList method. It simply returns an array of delegate objects, which you can then index to retrieve the delegate you want to remove.

9 CH05.qxd 11/14/03 1:08 PM Page 143 Chapter 5 Delegates and Events 143 One thing we haven t mentioned up to this point is that you can combine multicast delegates with other multicast delegates.the previous samples showed how to combine single delegates to form a multicast delegate, but the process is the same if you want to then take the resultant multicast delegate and combine it with the invocation list of another multicast delegate.this process results in a merge of the two invocation lists of those multicast delegates to form yet another object. Likewise, you can remove the invocation list of one multicast delegate from the invocation list of another, as mentioned earlier. If you call the Remove method defined in System.Delegate, the delegate class finds the matching list of delegates in a source multicast delegate and removes the last occurrence of that list in its invocation list. In other words, just as you can add the list of delegates from one multicast delegate to another, you can also turn around and remove that list. If a certain invocation list was added multiple times, then only the last occurrence of that list is removed from the multicast delegate. In other words, you have to call Remove for each associated Combine. If you would rather remove all invocation lists from a multicast delegate given another list, you can call the RemoveAll method.therefore, any time a matching invocation list appears in the source multicast delegate, it is removed regardless of its location in the entire list Accessing Delegate Names Within a Multicast Delegate You want to view which methods are attached to a multicast delegate. Technique To retrieve an array of delegates that are attached to a multicast delegate, call the GetInvocationList method from the multicast delegate instance.you can access the method name and additional method information on each delegate by using the Method property defined in the delegate.this step returns a MethodInfo object, and you find the name of the method bound to that delegate by accessing the Name property of that object: class StringPrinterDelegate public delegate void PrintString( string s ); // delegate passed as parameter public static void PrintWithDelegate( PrintString psdelegate, string s ) Console.Write( Invocation List Method Names: );

10 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events // enumerate through each delegate in invocation list foreach( Delegate dg in psdelegate.getinvocationlist() ) Console.Write( dg.method.name + ); Console.WriteLine(); // call delegate psdelegate( s ); Comments Whenever you start programming anything that is dynamic in nature, you lose any predefined knowledge about objects or methods or anything else that you normally know before you compile. In other words, when you want to call a method, you know what the method name is and you can use that information to output tracing or debug information. However, once you enter the dynamic realm where objects are attached during runtime, or the invocation of methods occurs dynamically based on the running state of the application, you don t always know what object is being accessed or what method is being called at any given point in time.that is, you don t know unless you have some sort of runtime type information or reflection capabilities built into the language or your application. The.NET Framework is a very dynamic environment and as such has rich support for runtime type information and the ability to inspect an object and its methods at any point.the multicast delegate class is no exception.there are a few reasons why you would want to inspect the methods that a multicast delegate is bound with, the most probable reason being debugging. You saw earlier how to use the GetInvocationList to access individual delegates within a multicast delegate so you can remove them from the invocation list. One thing that wasn t pointed out was that you can also enumerate this list to gather information about each delegate.the invocation list is simply an array of delegate objects whose type is System.Delegate.Within that class is a Method property that contains any information you need about the method to which the delegate is bound. Although this recipe singles out the Name property to determine the name of the bound method, there are other properties that you might find useful.

11 CH05.qxd 11/14/03 1:08 PM Page 145 Chapter 5 Delegates and Events Calling Delegates Asynchronously A delegate can take a long time to return; you want to invoke the delegate asynchronously so that it returns immediately and notifies you when it has finished. Technique In addition to the delegate and the method to bind to that delegate, create a method that is used to process the results of the asynchronous method call.this method takes a single IAsyncResult parameter.this method is called when the delegate method has finished, and you can obtain results by calling the EndInvoke method obtained from the IAsyncResult object. class TearCallback public void PrintTearResult( IAsyncResult ar) TearWebPage tear = (TearWebPage)((AsyncResult)ar).AsyncDelegate; Console.WriteLine( TearPage returned 0, tear.endinvoke( ar ) ); Before invoking the delegate, create an AsyncCallback object by passing the method name of the result method mentioned earlier. If this method is not static, use an instance of the object that implements this method followed by the dot operator (.) and the method name. Listing 5.2 Asynchronous Delegates using System; using System.Threading; using System.Runtime.Remoting.Messaging; using System.Net; using System.IO; using System.Text; namespace _5_AsynchronousDelegate public delegate bool TearWebPage( string url ); class Class1 [STAThread] static void Main(string[] args) // create delegate attached to DoAsynchSleep method

12 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events Listing 5.2 Continued TearWebPage tear = new TearWebPage( new WebTear().TearPage ); // create result class and create callback object TearCallback result = new TearCallback(); AsyncCallback ascb = new AsyncCallback( result.printtearresult ); // invoke the delegate asynchronously IAsyncResult ar = tear.begininvoke ( ascb, null ); // long operation here Thread.Sleep(10000); // Insert TearCallback implementation here class WebTear public bool TearPage( string url ) // final web page text variable StringBuilder pagetext = new StringBuilder( ); // create URI and a web request Uri HttpSite = new Uri(url); HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(HttpSite); wreq.allowautoredirect = true; // get the stream associated with the web request Stream webstream = wreq.getresponse().getresponsestream(); // create byte array for chunked data byte[] webresponse = new byte[1024]; int bytesread = 0; do // read first 1024 bytes bytesread = webstream.read( webresponse, 0, 1024 ); // append current chunk to final result if( bytesread > 0 ) pagetext.append( Encoding.ASCII.GetString ( webresponse, 0, bytesread ));

13 CH05.qxd 11/14/03 1:08 PM Page 147 Chapter 5 Delegates and Events 147 Listing 5.2 Continued // continue until no more bytes are being read while( bytesread > 0 ); // output final result Console.WriteLine( pagetext.tostring() ); return true; To invoke the delegate asynchronously, call the BeginInvoke method defined in the delegate, passing the necessary delegate parameters followed by the AsyncCallback object and an optional object used to hold state information, as shown in Listing 5.2. Comments As fast as computers are nowadays, sometimes fast still isn t fast enough.whether the lag occurs due to disk I/O, network traffic, or long computations, you can use this lag to your advantage by performing additional work until an operation finishes. Asynchronous method calls allow you to invoke a method and not wait for it to complete before you begin other tasks. As you work through the.net Framework, you will see that you can perform asynchronous method calls in a variety of different ways.this recipe shows how to invoke a delegate asynchronously. The initial code for the delegate is the same as the previous recipes in this chapter. The delegate is the same as well as its implementation and the code used to bind the two together.the difference is at the point where the actual work needs to happen, the point of delegate method invocation.the first recipe in this chapter mentioned that the delegate class generated upon using the delegate keyword contains three methods: Invoke, BeginInvoke, and EndInvoke. Upto this point, the Invoke method was called transparently anytime the delegate was used. Invoke performs a classic synchronous method call. In other words, Invoke does not return until the method has finished to completion.you use BeginInvoke and EndInvoke, however, when you want to call the delegate asynchronously. The code listing for this recipe creates a class that contains a method implementation for the TearWebPage delegate.this method, TearPage, uses classes within the.net Framework to open a connection with a remote Web server and request a page. If called synchronously, this method might not return for a while if network traffic is high, so we made the decision to call it asynchronously. The first step, other than actually creating the delegate method implementation, of course, is to create a method used as the callback method.when the delegate method finishes, this method is called to notify the user of the delegate.the method itself accepts a single parameter whose data type is IAsyncResult. Before looking at the implementa-

14 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events tion of this method, you first have to understand how BeginInvoke works. After you bind a method to a delegate, you have to set up the necessary objects used for the delegate callback.to do so, create an instance of the class that contains the callback method if this method isn t static. Next, create an AsyncCallback object passing the callback method name as the parameter.you can then call the BeginInvoke method. BeginInvoke is dynamically created based on the parameters.when you call BeginInvoke, as shown in the listing earlier, you provide each parameter necessary similar to the way you do if you were performing a synchronous method call. However, you need two additional parameters after the delegate parameter list.the first is the AsyncCallback method created earlier; the delegate class uses it when the method finishes.the final parameter can be any object that you want to create to hold state information. Because this parameter is optional and not used within the implementation of the BeginInvoke method itself, this parameter can be null. Once the BeginInvoke method is called, it returns immediately even though the method to which the delegate is bound has not finished.you can then perform additional processing as you wait for the delegate method to finish. Once the delegate method finishes, your callback method created earlier is called. If you recall, this method receives a IAsyncResult parameter, which you can use to access the delegate instance that has finished.to do so, cast the IAsyncResult to an AsyncResult object and then cast the AsyncDelegate property of that object to your delegate class, as shown in the PrintTearResult method earlier.to access the return value, call the EndInvoke method defined in the delegate class.the EndInvoke is also dynamically created using the return value of the delegate method as its return value. Figure 5.4 shows the result of running Listing 5.2. Figure 5.4 You download a Web page using an asynchronous delegate and access its result using the delegate callback method.

15 CH05.qxd 11/14/03 1:08 PM Page 149 Chapter 5 Delegates and Events Return Values for Multicast Delegates You want to access individual return values for each delegate method within a multicast delegate. Technique If you want to use the return value from one delegate method as the input to another delegate method within the same multicast delegate, create a parameter prefaced with the ref keyword for value types. If an object is passed as a parameter, note that any change to that object is passed onto the next delegate method within the invocation list: public void Factorial( ref int op1, ref int op2 ); If you want to obtain individual return values for each single delegate within a multicast delegate, you can create a collection as a parameter in the delegate list that method implementations can use to place return values as demonstrated in Listing 5.3. Listing 5.3 Allowing Individual Delegate Return Values by Using a Collection using System; using System.Collections; using System.Text; namespace _6_ReturnValues public delegate bool PrintString( string s, ArrayList retvals ); class Class1 [STAThread] static void Main(string[] args) ArrayList retvals = new ArrayList(); // instantiate delegate PrintString[] printdelegates = new PrintString[2]; PrintString stringprinters; printdelegates[0] = new PrintString( NormalPrint ); printdelegates[1] = new PrintString( FirstCharPrint ); stringprinters = (PrintString) Delegate.Combine( printdelegates ); // get string from user Console.Write( Enter a string: );

16 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events Listing 5.3 Continued string input = Console.ReadLine(); stringprinters( input, retvals ); foreach( string ret in retvals ) Console.WriteLine( ret ); static bool NormalPrint( string s, ArrayList retvals ) retvals.add( s ); return true; static bool FirstCharPrint( string s, ArrayList retvals ) StringBuilder retval = new StringBuilder(); string[] splitstrings = s.split( new char[] ); foreach( string splitstring in splitstrings ) retval.append(splitstring[0]); for( int i = 0; i < splitstring.length; i++ ) retval.append( ); retvals.add( retval.tostring() ); return true; Comments One of the limitations of using a multicast delegate is the lack of information based on a return value from the individual methods bound to that multicast delegate.the return value from a multicast delegate is the result of the last delegate method called within the invocation list.you are therefore unable to access the previous delegate method return values without resorting to the special programming methods presented here. Although not necessarily capturing the return value of each delegate, using the ref keyword on a parameter allows you to carry changes to a value type to each subsequent

17 CH05.qxd 11/14/03 1:08 PM Page 151 Chapter 5 Delegates and Events 151 delegate.this move can be useful, for instance, if you need a value that each delegate must change and that change must be carried over. In the Factorial method header declared earlier, you can create a factorial function that multiplies the first parameter by the last result and then decrements the first parameter by one.the multicast delegate would contain a instance of that delegate equal to the initial value of the original first parameter. Of course, this process is highly inefficient, but it does a good job of showing how to carry value types across multiple delegates within a multicast delegate. If you would rather obtain information individually from each delegate, then you can create an array to store that information. Although it s not the most elegant solution, there aren t many other choices to solve this problem. Listing 5.3 uses an ArrayList as a parameter to the delegate. As each delegate method is invoked, it places its result at the end of the list.you can then access each delegate s result after the multicast delegate has finished calling each method within its invocation list.we used an ArrayList due to its ability to grow if the size of the array is unknown, but you can just as easily use a regular system array. Furthermore, you can pass multiple return values by using a structure that contains the return values as the item data type within the array. Finally, it s worth noting that because ArrayList is an object and not a value type, you do not need the ref keyword because objects are passed by reference by default Declaring Events You want to create an event within your class. Technique First, create a delegate that is used for the event, as shown in the previous recipe. Next, create a member variable of the type within your class placing the keyword event after the variable s access modifier: class ConsoleMenu public delegate void MenuEventHandler( object sender, string[] args ); public event MenuEventHandler OnMenuEvent; Comments Delegates allow flexibility within a program that otherwise wouldn t be available, or at least would be difficult to implement, to alter the flow of control dynamically while an application is running. Because delegates provide an inherent connection between two disparate objects, it seems only natural to utilize this design when creating an event infrastructure, which is exactly the case with the.net Framework.

18 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events The first step in the process to add events to your object is to give the event you want to fire a name and to declare the method signature for that event.you declare the method signature for an event using a delegate. In the previous recipe, you saw that a delegate is simply a method declaration using the delegate keyword. Furthermore, because a delegate is bound to a different implementation, it does not contain an implementation of its own, which means there is no method body associated with that method. A delegate associated with an event is used as the event handler for the object that has requested to be notified for that event.the process of requesting notification or subscribing to an event is covered in the next recipe. Events have an associated name to distinguish them from the actual delegates they are bound to.you declare events by creating a member variable within your class whose data type is that of the delegate to which it is bound. Unlike with regular variables, however, you must use the event keyword to allow special processing by the compiler.when you do so, the compiler generates additional information, in IL, which creates the necessary information to control how that event is connected to handlers and how the event is fired. Just like the delegate keyword, the event keyword generates a nested class. However, this class is private and is used internally by methods that the compiler has also emitted. Listing 5.4 shows the code used in this and the following two recipes.the class that supports events is ConsoleMenu, and as you can guess by the name, it supports a console-based menu system, albeit somewhat rudimentary.the event fired is OnMenuEvent, which is bound to the MenuEventHandler delegate. Listing 5.4 ConsoleMenu Class Fires the OnMenuEvent Event using System; using System.Collections; namespace _7_AddingEvents class Class1 static void Main(string[] args) class ConsoleMenu ArrayList menuitems = new ArrayList(); bool quitmenu = false; // menu item event handler delegate public delegate void MenuEventHandler( object sender, string[] args ); // event fired when user selects a menu item public event MenuEventHandler OnMenuEvent;

19 CH05.qxd 11/14/03 1:08 PM Page 153 Chapter 5 Delegates and Events 153 Listing 5.4 Continued // adds a menu item to the internal ArrayList public void AddMenuItem( string text ) menuitems.add( text ); public void QuitMenu() quitmenu = true; public void DisplayMenu() string input; do int idx = 1; int choice = 0; // display each menu item string prefaced by its index value foreach( string menuchoice in menuitems ) Console.WriteLine( 0: 1, idx++, menuchoice ); Console.Write( Enter choice: ); // get users input and convert to integer input = Console.ReadLine(); choice = Int32.Parse( input[0].tostring() ); if( choice > 0 && choice <= menuitems.count ) // build event arguments string[] args = new string[2]; args[0] = input[0].tostring(); args[1] = menuitems[int32.parse(input[0].tostring())-1].tostring(); // fire event to be handled by client using this class OnMenuEvent( this, args); else Console.WriteLine( Invalid choice!\n );

20 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events Listing 5.4 Continued while ( quitmenu == false ); quitmenu = false; You can add new menu items by using the AddMenuItem method, which uses a string as the name of the menu item when it is displayed.to display the menu and accept user input, you use the DisplayInput method.this method continually loops until the quitmenu private variable is set to true.the actual firing of the event occurs after the user has entered her input value and after that value is validated. Firing an event is slightly different from the method used to call a delegate method. When you used a delegate, you could simply call it like any other method, and the runtime would invoke the actual method implementation it was bound to. However, the event itself is just a variable and not an actual method even though the preceding code uses a method-calling syntax.to fire an event, use the event name as the method name, but use the parameter list of the delegate that the event is bound to. In this case, the event name OnMenuEvent is the method name, and the parameter data types are those of the MenuEventHandler delegate. Once you call it, any clients that have subscribed to that event will be notified Defining and Registering Event Handlers Youwant to consume the events that are fired from an object. Technique Define a method that has the same method signature as the delegate to which an event is bound to. It becomes the event handler.to register this handler to receive events when they are fired, use the addition assignment operator (+=) on the event name of the object instance you want to subscribe to and assign that to an instance of a bound delegate passing the event-handler name to the delegate constructor, as shown in the Main method of Listing 5.5. Listing 5.5 Creating Event Handlers class Class1 [STAThread] static void Main(string[] args)

21 CH05.qxd 11/14/03 1:08 PM Page 155 Chapter 5 Delegates and Events 155 Listing 5.5 Continued ConsoleMenu menu = new ConsoleMenu(); menu.addmenuitem( Item 1 ); menu.addmenuitem( Item 2 ); menu.addmenuitem( Item 3 ); menu.addmenuitem( Quit ); menu.onmenuevent += new ConsoleMenu.MenuEventHandler(MenuItemHandler); menu.displaymenu(); static void MenuItemHandler( object sender, string[] args ) switch( Int32.Parse( args[0].tostring() )) case( 1 ): case( 2 ): case( 3 ): Console.WriteLine( You selected the item 0\n, args[1] ); break; case( 4 ): Console.WriteLine( Goodbye! ); ((ConsoleMenu)sender).QuitMenu(); break; Comments Listing 5.5 shows how to subscribe to the events that are fired from the ConsoleMenu class in Listing 5.4.When binding a method implementation to a delegate, you create the method using the same signature as the delegate, and with events, this process is the same.the delegate in Listing 5.4 contains two parameters, an object and an array of strings, and the method MenuItemHandler in Listing 5.5 follows that same convention. Instead of binding a method to a delegate, however, event handlers are bound to the actual event name defined within the class that fires that event.you do so using the addition assignment operator (+=), which assigns the event to an instance of its delegate class.

22 CH05.qxd 11/14/03 1:08 PM Page Chapter 5 Delegates and Events If you compare this step to the delegate recipe earlier in this chapter, you should see some peculiar similarities. Earlier, a variable whose data type was that of the generated delegate class was created within the client who was using the delegate. In Listing 5.4, that variable is declared within the class that fires the event, and the event keyword is added to it. Furthermore, just as you bind a method to a delegate using the new keyword passing the name of the method within the constructor, the same process occurs with events and the name of the event handler is passed as the delegate constructor. At this point, the event communication between a class and a client is set.the event that is implemented by the class which fires it is bound to an event handler.therefore, when the class that fires the event calls the corresponding event method, the runtime routes the call to the method handlers that have subscribed to that event. It is there that processing can occur based on the arguments passed into the event handler.within the event handler of Listing 5.5, you can see that the menu is dismissed by calling the QuitMenu method on the ConsoleMenu instance.this method sets the Boolean value quitmenu that is used to control the display of the menu. Figure 5.5 shows the result of running the ConsoleMenu class and its associated client code. Figure 5.5 Using events to create a simple console-based menu system Packaging Event Arguments Youwant to package state information into a class that you can use as arguments to an event handler. Technique Create a new class derived from System.EventArgs. Add any public member variables to the class that the event handler can then access.the event delegate should use this class as a parameter in its parameter list.when the event is fired, create an instance of this class, ensuring that its member variables have been properly set to reflect the current event information:

23 CH05.qxd 11/14/03 1:08 PM Page 157 Chapter 5 Delegates and Events 157 public class MenuItemEventArgs : EventArgs public int id; public string displaystring; public MenuItemEventArgs( int id, string displaystring ) this.id = id; this.displaystring = displaystring; Comments Packaging event arguments into a class derived from EventArgs, believe it or not, is purely for aesthetic reasons. If you look at the EventArgs class, you ll see that it doesn t add any additional functionality beyond the methods and properties contained in System.Object.That said, you are free to forego this procedure of argument-packing altogether and simply pass parameters normally when you fire an event. However, it is recommended, just as coding and naming guidelines are recommended, that you create a consistent method for event arguments by using the steps shown here.

24 CH05.qxd 11/14/03 1:08 PM Page 158

Asynchronous Programming Model (APM) 1 Calling Asynchronous Methods Using IAsyncResult 4 Blocking Application Execution by Ending an Async Operation

Asynchronous Programming Model (APM) 1 Calling Asynchronous Methods Using IAsyncResult 4 Blocking Application Execution by Ending an Async Operation Asynchronous Programming Model (APM) 1 Calling Asynchronous Methods Using IAsyncResult 4 Blocking Application Execution by Ending an Async Operation 5 Blocking Application Execution Using an AsyncWaitHandle

More information

C# Asynchronous Programming Model

C# Asynchronous Programming Model Spring 2014 C# Asynchronous Programming Model A PRACTICAL GUIDE BY CHRIS TEDFORD TABLE OF CONTENTS Introduction... 2 Background Information... 2 Basic Example... 3 Specifications and Usage... 4 BeginInvoke()...

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Understanding Events in C#

Understanding Events in C# Understanding Events in C# Introduction Events are one of the core and important concepts of C#.Net Programming environment and frankly speaking sometimes it s hard to understand them without proper explanation

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Threads are lightweight processes responsible for multitasking within a single application.

Threads are lightweight processes responsible for multitasking within a single application. Threads Threads are lightweight processes responsible for multitasking within a single application. The class Thread represents an object-oriented wrapper around a given path of execution. The class Thread

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Professional ASP.NET Web Services : Asynchronous Programming

Professional ASP.NET Web Services : Asynchronous Programming Professional ASP.NET Web Services : Asynchronous Programming To wait or not to wait; that is the question! Whether or not to implement asynchronous processing is one of the fundamental issues that a developer

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduce C# as Object Oriented programming language. Explain, tokens, Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data

More information

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. 1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity

More information

C# Language. CSE 409 Advanced Internet Technology

C# Language. CSE 409 Advanced Internet Technology C# Language Today You will learn Building a basic class Value Types and Reference Types Understanding Namespaces and Assemblies Advanced Class Programming CSE 409 Advanced Internet Technology Building

More information

Sri Lanka Institute of Information Technology System Programming and Design II Year 3 Tutorial 06

Sri Lanka Institute of Information Technology System Programming and Design II Year 3 Tutorial 06 Sri Lanka Institute of Information Technology System Programming and Design II Year 3 Tutorial 06 1. What is an asynchronous call? How does it differ from a synchronous call? In synchronous call, the caller

More information

Concurrent Programming

Concurrent Programming Concurrent Programming Adam Przybyłek, 2016 przybylek.wzr.pl This work is licensed under a Creative Commons Attribution 4.0 International License. Task Parallel Library (TPL) scales the degree of concurrency

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

C# Programming for Developers Course Labs Contents

C# Programming for Developers Course Labs Contents C# Programming for Developers Course Labs Contents C# Programming for Developers...1 Course Labs Contents...1 Introduction to C#...3 Aims...3 Your First C# Program...3 C# The Basics...5 The Aims...5 Declaring

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

C#: framework overview and in-the-small features

C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Introduction To C#.NET

Introduction To C#.NET Introduction To C#.NET Microsoft.Net was formerly known as Next Generation Windows Services(NGWS).It is a completely new platform for developing the next generation of windows/web applications. However

More information

Course Hours

Course Hours Programming the.net Framework 4.0/4.5 with C# 5.0 Course 70240 40 Hours Microsoft's.NET Framework presents developers with unprecedented opportunities. From 'geoscalable' web applications to desktop and

More information

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

CS 211 Programming Practicum Fall 2018

CS 211 Programming Practicum Fall 2018 Due: Wednesday, 11/7/18 at 11:59 pm Infix Expression Evaluator Programming Project 5 For this lab, write a C++ program that will evaluate an infix expression. The algorithm REQUIRED for this program will

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.5: Methods A Deeper Look Xianrong (Shawn) Zheng Spring 2017 1 Outline static Methods, static Variables, and Class Math Methods with Multiple

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Representative Delegates

Representative Delegates The Inside Track Representative and Reactionary Programming June 2001 I m back from my vacation. It was great, I saw many of the great natural wonders the south and west part of this country has to offer.

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

C# Java. C# Types Naming Conventions. Distribution and Integration Technologies. C# C++.NET A C# program is a collection of: C C++ C# Language

C# Java. C# Types Naming Conventions. Distribution and Integration Technologies. C# C++.NET A C# program is a collection of: C C++ C# Language C# Java Distribution and Integration Technologies C# Language C C++ C# C++.NET A C# program is a collection of: Classes Structs Interfaces Delegates Enums (can be grouped in namespaces) One entry point

More information

Distribution and Integration Technologies. C# Language

Distribution and Integration Technologies. C# Language Distribution and Integration Technologies C# Language Classes Structs Interfaces Delegates Enums C# Java C C++ C# C++.NET A C# program is a collection of: (can be grouped in namespaces) One entry point

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

COPYRIGHTED MATERIAL. Part I The C# Ecosystem. ChapTEr 1: The C# Environment. ChapTEr 2: Writing a First Program

COPYRIGHTED MATERIAL. Part I The C# Ecosystem. ChapTEr 1: The C# Environment. ChapTEr 2: Writing a First Program Part I The C# Ecosystem ChapTEr 1: The C# Environment ChapTEr 2: Writing a First Program ChapTEr 3: Program and Code File Structure COPYRIGHTED MATERIAL 1The C# Environment What s in This ChapTEr IL and

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

IT150/IT152 Concepts Summary Sheet

IT150/IT152 Concepts Summary Sheet (Examples within this study guide/summary sheet are given in C#.) Variables All data in a computer program, whether calculated during runtime or entered by the user, must be stored somewhere in the memory

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

DC69 C# &.NET DEC 2015

DC69 C# &.NET DEC 2015 Q.2 a. Briefly explain the advantage of framework base classes in.net. (5).NET supplies a library of base classes that we can use to implement applications quickly. We can use them by simply instantiating

More information

LAB C Translating Utility Classes

LAB C Translating Utility Classes LAB C Translating Utility Classes Perform the following groups of tasks: LabC1.s 1. Create a directory to hold the files for this lab. 2. Create and run the following two Java classes: public class IntegerMath

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

DC69 C# and.net JUN 2015

DC69 C# and.net JUN 2015 Solutions Q.2 a. What are the benefits of.net strategy advanced by Microsoft? (6) Microsoft has advanced the.net strategy in order to provide a number of benefits to developers and users. Some of the major

More information

Introduction to Programming (Java) 4/12

Introduction to Programming (Java) 4/12 Introduction to Programming (Java) 4/12 Michal Krátký Department of Computer Science Technical University of Ostrava Introduction to Programming (Java) 2008/2009 c 2006 2008 Michal Krátký Introduction

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Learn C# Errata. 3-9 The Nullable Types The Assignment Operators

Learn C# Errata. 3-9 The Nullable Types The Assignment Operators 1 The following pages show errors from the original edition, published in July 2008, corrected in red. Future editions of this book will be printed with these corrections. We apologize for any inconvenience

More information

D Programming Language

D Programming Language Group 14 Muazam Ali Anil Ozdemir D Programming Language Introduction and Why D? It doesn t come with a religion this is written somewhere along the overview of D programming language. If you actually take

More information

Problem 1: Building and testing your own linked indexed list

Problem 1: Building and testing your own linked indexed list CSCI 200 Lab 8 Implementing a Linked Indexed List In this lab, you will be constructing a linked indexed list. You ll then use your list to build and test a new linked queue implementation. Objectives:

More information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science Department Lecture 3: C# language basics Lecture Contents 2 C# basics Conditions Loops Methods Arrays Dr. Amal Khalifa, Spr 2015 3 Conditions and

More information

About this exam review

About this exam review Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

Fundamental Concepts and Definitions

Fundamental Concepts and Definitions Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

M/s. Managing distributed workloads. Language Reference Manual. Miranda Li (mjl2206) Benjamin Hanser (bwh2124) Mengdi Lin (ml3567)

M/s. Managing distributed workloads. Language Reference Manual. Miranda Li (mjl2206) Benjamin Hanser (bwh2124) Mengdi Lin (ml3567) 1 M/s Managing distributed workloads Language Reference Manual Miranda Li (mjl2206) Benjamin Hanser (bwh2124) Mengdi Lin (ml3567) Table of Contents 1. Introduction 2. Lexical elements 2.1 Comments 2.2

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

The list abstract data type defined a number of operations that all list-like objects ought to implement:

The list abstract data type defined a number of operations that all list-like objects ought to implement: Chapter 7 Polymorphism Previously, we developed two data structures that implemented the list abstract data type: linked lists and array lists. However, these implementations were unsatisfying along two

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Java We will be programming in Java in this course. Partly because it is a reasonable language, and partly because you

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

DC69 C# &.NET JUNE C# is a simple, modern, object oriented language derived from C++ and Java.

DC69 C# &.NET JUNE C# is a simple, modern, object oriented language derived from C++ and Java. Q.2 a. What is C#? Discuss its features in brief. 1. C# is a simple, modern, object oriented language derived from C++ and Java. 2. It aims to combine the high productivity of Visual Basic and the raw

More information

OGSI.NET UVa Grid Computing Group. OGSI.NET Developer Tutorial

OGSI.NET UVa Grid Computing Group. OGSI.NET Developer Tutorial OGSI.NET UVa Grid Computing Group OGSI.NET Developer Tutorial Table of Contents Table of Contents...2 Introduction...3 Writing a Simple Service...4 Simple Math Port Type...4 Simple Math Service and Bindings...7

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

Creating delegate, actually creating an object that can hold a reference to a method.

Creating delegate, actually creating an object that can hold a reference to a method. Delegates A delegate is an object that can refer to a method. Creating delegate, actually creating an object that can hold a reference to a method. The method can be called through this reference. A delegate

More information

CS 221 Review. Mason Vail

CS 221 Review. Mason Vail CS 221 Review Mason Vail Inheritance (1) Every class - except the Object class - directly inherits from one parent class. Object is the only class with no parent. If a class does not declare a parent using

More information

Your first C++ program

Your first C++ program Your first C++ program #include using namespace std; int main () cout

More information

We would like guidance on how to write our programs beyond simply knowing correlations between inputs and outputs.

We would like guidance on how to write our programs beyond simply knowing correlations between inputs and outputs. Chapter 3 Correctness One of the most appealing aspects of computer programs is that they have a close connection to mathematics, in particular, logic. We use these connections implicitly every day when

More information

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

C# Programming: From Problem Analysis to Program Design. Fourth Edition

C# Programming: From Problem Analysis to Program Design. Fourth Edition C# Programming: From Problem Analysis to Program Design Fourth Edition Preface xxi INTRODUCTION TO COMPUTING AND PROGRAMMING 1 History of Computers 2 System and Application Software 4 System Software 4

More information

Appendix G: Writing Managed C++ Code for the.net Framework

Appendix G: Writing Managed C++ Code for the.net Framework Appendix G: Writing Managed C++ Code for the.net Framework What Is.NET?.NET is a powerful object-oriented computing platform designed by Microsoft. In addition to providing traditional software development

More information

Asynchronous Functions in C#

Asynchronous Functions in C# Asynchronous Functions in C# Asynchronous operations are methods and other function members that may have most of their execution take place after they return. In.NET the recommended pattern for asynchronous

More information

Table of Contents Preface Bare Necessities... 17

Table of Contents Preface Bare Necessities... 17 Table of Contents Preface... 13 What this book is about?... 13 Who is this book for?... 14 What to read next?... 14 Personages... 14 Style conventions... 15 More information... 15 Bare Necessities... 17

More information

Java+- Language Reference Manual

Java+- Language Reference Manual Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect

More information

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time) CSE 11 Winter 2017 Program Assignment #2 (100 points) START EARLY! Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time) PROGRAM #2: DoubleArray11 READ THE ENTIRE ASSIGNMENT BEFORE STARTING In lecture,

More information

PES INSTITUTE OF TECHNOLOGY

PES INSTITUTE OF TECHNOLOGY Seventh Semester B.E. IA Test-I, 2014 USN 1 P E I S PES INSTITUTE OF TECHNOLOGY C# solution set for T1 Answer any 5 of the Following Questions 1) What is.net? With a neat diagram explain the important

More information

3 ADT Implementation in Java

3 ADT Implementation in Java Object-Oriented Design Lecture 3 CS 3500 Spring 2010 (Pucella) Tuesday, Jan 19, 2010 3 ADT Implementation in Java Last time, we defined an ADT via a signature and a specification. We noted that the job

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information