4102 Chap01 47 - itcourseware.com

60
Object Innovations Course 4102 Student Guide Revision 4.7 C# Essentials EVALUATION COPY Unauthorized reproduction or distribution is prohibited

Transcript of 4102 Chap01 47 - itcourseware.com

Page 1: 4102 Chap01 47 - itcourseware.com

Object Innovations Course 4102

Student Guide Revision 4.7

C# Essentials

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 2: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC ii All Rights Reserved

C# Essentials Rev. 4.7 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners.

™ is a trademark of Object Innovations. Author: Robert J. Oberg Special Thanks: Johnathon McAlister Copyright ©2015 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 3: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 .NET: What You Need to Know

Chapter 2 C# Overview for the Sophisticated Programmer

Chapter 3 Object-Oriented Programming in C#

Chapter 4 C# and the .NET Framework

Chapter 5 Delegates and Events

Chapter 6 Introduction to Windows Forms

Chapter 7 Newer Features in C#

Appendix A Using Visual Studio 2015

Appendix B Language Integrated Query (LINQ)

Appendix C Unsafe Code and Pointers in C#

Appendix D Learning Resources

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 4: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

The course software installs to the root directory C:\OIC\CsEss.

Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on.

Example programs for Appendices A, B and C are in the directories AppA, AppB and AppC.

The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

The CaseStudy directory contains a case study in multiple steps.

The Demos directory is provided for performing in-class demonstrations led by the instructor.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 5: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1 .NET: What You Need to Know .............................................................. 1 Getting Started ................................................................................................................ 3 .NET: What Is Really Happening ................................................................................... 4 .NET Programming in a Nutshell ................................................................................... 5 .NET Program Example.................................................................................................. 6 Viewing the Assembly.................................................................................................... 7 Viewing Intermediate Language..................................................................................... 8 Understanding .NET ....................................................................................................... 9 Visual Studio 2015........................................................................................................ 10 Visual Studio Sign In .................................................................................................... 11 Creating a Console Application .................................................................................... 12 Adding a C# File........................................................................................................... 13 Using the Visual Studio Text Editor............................................................................. 14 IntelliSense.................................................................................................................... 15 Build and Run the Project ............................................................................................. 16 Pausing the Output........................................................................................................ 17 Visual C# and GUI Programs ....................................................................................... 18 .NET Documentation .................................................................................................... 19 Summary ....................................................................................................................... 20

Chapter 2 C# Overview for the Sophisticated Programmer................................. 21 Hello, World ................................................................................................................. 23 Compiling, Running (Command Line) ......................................................................... 24 Program Structure ......................................................................................................... 25 Namespaces................................................................................................................... 28 Variables ....................................................................................................................... 29 Input in C# .................................................................................................................... 30 More about Classes ....................................................................................................... 31 InputWrapper Class ...................................................................................................... 32 Sample Program............................................................................................................ 33 Input Wrapper Implementation..................................................................................... 34 Compiling Multiple Files.............................................................................................. 35 Control Structures ......................................................................................................... 36 switch ............................................................................................................................ 37 C# Operators ................................................................................................................. 38 Precedence Table .......................................................................................................... 39 Types in C#................................................................................................................... 40 Simple Types ................................................................................................................ 41 Types in System Namespace ........................................................................................ 42 Integer Data Types........................................................................................................ 43 Floating Point Data Types ............................................................................................ 44 Implicit Conversions..................................................................................................... 45 Explicit Conversions..................................................................................................... 46

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 6: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC vi All Rights Reserved

Boolean Data Type ....................................................................................................... 47 struct.............................................................................................................................. 48 Uninitialized Variables ................................................................................................. 49 Enumeration Types ....................................................................................................... 50 Nullable Types .............................................................................................................. 51 Reference Types............................................................................................................ 52 Class Types ................................................................................................................... 53 object............................................................................................................................. 54 string ............................................................................................................................. 55 Copying Strings ............................................................................................................ 56 StringBuilder Class ....................................................................................................... 57 Classes and Structs........................................................................................................ 59 Static and Instance Methods ......................................................................................... 60 Method Parameters ....................................................................................................... 61 No “Freestanding” Functions in C#.............................................................................. 62 Classes with All Static Methods ................................................................................... 63 Parameter Passing ......................................................................................................... 64 Parameter Terminology ................................................................................................ 65 Value Parameters .......................................................................................................... 66 Reference Parameters.................................................................................................... 67 Reference Parameters Example .................................................................................... 68 Output Parameters......................................................................................................... 69 Output Parameters Example ......................................................................................... 70 Structure Parameters ..................................................................................................... 71 Class Parameters ........................................................................................................... 72 Method Overloading ..................................................................................................... 73 Variable Length Parameter Lists .................................................................................. 75 Arrays............................................................................................................................ 76 One-Dimensional Arrays .............................................................................................. 77 System.Array ................................................................................................................ 78 Jagged Arrays................................................................................................................ 79 Rectangular Arrays ....................................................................................................... 80 foreach for Arrays ......................................................................................................... 81 Boxing and Unboxing ................................................................................................... 82 Implicitly Typed Variables ........................................................................................... 83 Implicitly Typed Variables – Example ......................................................................... 84 Output in C#.................................................................................................................. 85 Formatting..................................................................................................................... 86 Formatting Example...................................................................................................... 87 Exceptions..................................................................................................................... 88 Exception Example ....................................................................................................... 89 Checked Integer Arithmetic.......................................................................................... 90 Throwing New Exceptions ........................................................................................... 91 finally ............................................................................................................................ 92 System.Exception.......................................................................................................... 93 Lab 2 ............................................................................................................................. 94

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 7: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC vii All Rights Reserved

Summary ....................................................................................................................... 95

Chapter 3 Object-Oriented Programming in C# ................................................... 99 C# Object-Oriented Features ...................................................................................... 101 Encapsulation and Accessors...................................................................................... 102 Asymmetric Accessor Accessibility ........................................................................... 103 Using a Property ......................................................................................................... 104 Indexers....................................................................................................................... 105 Visual Studio Console Projects................................................................................... 106 Files in Skeleton Solution ........................................................................................... 107 Source Files................................................................................................................. 108 Bank Example............................................................................................................. 109 Account Class ............................................................................................................. 110 Constructors ................................................................................................................ 112 Static Members ........................................................................................................... 113 Static in Main .............................................................................................................. 114 Static Constructor........................................................................................................ 115 Constant and Readonly Fields .................................................................................... 116 Auto-Implemented Properties..................................................................................... 117 Auto-Implemented Property Example ........................................................................ 118 Inheritance in C#......................................................................................................... 119 New Version of Base Class......................................................................................... 120 Features of the New Base Class.................................................................................. 121 Derived Class .............................................................................................................. 122 Overriding a Virtual Function..................................................................................... 123 Abstract Classes .......................................................................................................... 124 Keyword: abstract ...................................................................................................... 125 Derived Class .............................................................................................................. 126 Test Program............................................................................................................... 127 Sealed Classes............................................................................................................. 128 Access Control and Assemblies.................................................................................. 129 Internal Accessibility .................................................................................................. 130 Assembly Example ..................................................................................................... 131 Class Libraries ............................................................................................................ 132 Lab 3 ........................................................................................................................... 133 Summary ..................................................................................................................... 134

Chapter 4 C# and the .NET Framework .............................................................. 139 Components and OO in C# ......................................................................................... 141 Interfaces in C# ........................................................................................................... 143 Interface Inheritance ................................................................................................... 144 Programming with Interfaces...................................................................................... 145 Implementing Interfaces ............................................................................................. 146 Using an Interface ....................................................................................................... 148 Example: SmallInterface............................................................................................ 149 Dynamic Use of Interfaces.......................................................................................... 150 Example: TryInterfaces.............................................................................................. 151 is Operator................................................................................................................... 152

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 8: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC viii All Rights Reserved

as Operator .................................................................................................................. 153 Resolving Ambiguity .................................................................................................. 154 Explicit Interface Implementation .............................................................................. 155 Explicit Interfaces Test Program ................................................................................ 156 System.Object ............................................................................................................. 157 Collections .................................................................................................................. 159 ArrayList ..................................................................................................................... 160 ArrayList Methods ...................................................................................................... 161 Example: StringList ................................................................................................... 162 IEnumerable and IEnumerator.................................................................................... 163 Using Enumerators...................................................................................................... 164 Collections of User-Defined Objects .......................................................................... 165 Account Class ............................................................................................................. 166 AccountList Class ....................................................................................................... 168 Copy Semantics in C#................................................................................................. 170 Deep Copy and ICloneable ......................................................................................... 171 Lab 4A ........................................................................................................................ 172 Writing Generic Code ................................................................................................. 173 Using a Class of object ............................................................................................... 174 Generic Types ............................................................................................................. 175 Generic Syntax in C#.................................................................................................. 176 Generic Example......................................................................................................... 177 Generic Client Code.................................................................................................... 178 System.Collections.Generic........................................................................................ 179 Lab 4B......................................................................................................................... 180 Object Initializers........................................................................................................ 181 Collection Initializers.................................................................................................. 182 Anonymous Types ...................................................................................................... 183 Attributes..................................................................................................................... 184 Attribute Usage Example............................................................................................ 185 Summary ..................................................................................................................... 186

Chapter 5 Delegates and Events ............................................................................ 191 Overview of Delegates and Events ............................................................................. 193 Callbacks and Delegates ............................................................................................. 194 Usage of Delegates ..................................................................................................... 195 Declaring a Delegate................................................................................................... 196 Defining a Method ...................................................................................................... 197 Creating a Delegate Object ......................................................................................... 198 Calling a Delegate....................................................................................................... 199 Random Number Generation ...................................................................................... 200 A Random Array......................................................................................................... 201 Anonymous Methods .................................................................................................. 202 Combining Delegate Objects ...................................................................................... 203 Account.cs................................................................................................................... 204 DelegateAccount.cs .................................................................................................... 205 Lambda Expressions ................................................................................................... 206

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 9: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC ix All Rights Reserved

Named Method............................................................................................................ 207 Anonymous Method.................................................................................................... 208 Lambda Expression Example ..................................................................................... 209 Events.......................................................................................................................... 210 Events in C# and .NET ............................................................................................... 211 Client Side Event Code............................................................................................... 213 Chat Room Example ................................................................................................... 214 Lab 5 ........................................................................................................................... 215 Summary ..................................................................................................................... 216

Chapter 6 Introduction to Windows Forms ......................................................... 219 Creating a Windows Forms App................................................................................. 221 Partial Classes ............................................................................................................. 225 Windows Forms Event Handling................................................................................ 226 Add Events for a Control ............................................................................................ 227 Events Documentation................................................................................................ 228 Closing a Form............................................................................................................ 229 ListBox Control .......................................................................................................... 230 ListBox Example ........................................................................................................ 231 Lab 6 ........................................................................................................................... 232 Summary ..................................................................................................................... 233

Chapter 7 Newer Features in C# ........................................................................... 237 dynamic Type.............................................................................................................. 239 Runtime Error Example .............................................................................................. 240 dynamic versus object ................................................................................................. 241 Behavior of object....................................................................................................... 242 Behavior of dynamic ................................................................................................... 243 Named Arguments ...................................................................................................... 244 Optional Arguments.................................................................................................... 245 Book Class .................................................................................................................. 246 Using Optional Arguments ......................................................................................... 247 Variance in Generic Interfaces.................................................................................... 248 Covariance Example ................................................................................................... 249 Variance with IComparer<T>..................................................................................... 250 Interfaces with Variance Support................................................................................ 251 Contravariance Example............................................................................................. 252 Asynchronous Programs in C# 5.0 ............................................................................. 253 Task and Task<TResult> ............................................................................................ 254 Aysnc Methods ........................................................................................................... 255 Async Example ........................................................................................................... 256 Synchronous Call ........................................................................................................ 257 Async Call................................................................................................................... 258 Threading .................................................................................................................... 259 New Features in C# 6.0............................................................................................... 260 Null-Conditional Operator .......................................................................................... 261 Summary ..................................................................................................................... 262

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 10: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC x All Rights Reserved

Appendix A Using Visual Studio 2015...................................................................... 263 Visual Studio Sign in .................................................................................................. 265 Sign In Advantages ..................................................................................................... 266 Visual Studio Start Page ............................................................................................. 267 A Visual Studio Solution ............................................................................................ 268 Toolbars ...................................................................................................................... 270 Customizing a Toolbar................................................................................................ 271 Creating a Console Application .................................................................................. 274 Adding a C# File......................................................................................................... 275 Using the Visual Studio Text Editor........................................................................... 276 Build and Run the Bytes Project................................................................................. 277 Running the Bytes Project .......................................................................................... 278 Executable File Location ............................................................................................ 279 Managing Configurations ........................................................................................... 280 Project Configurations ................................................................................................ 281 Creating a New Configuration .................................................................................... 282 Setting Configuration Build Settings .......................................................................... 283 Debugging................................................................................................................... 284 Breakpoints ................................................................................................................. 285 Watch Variables.......................................................................................................... 286 Debug Toolbar ............................................................................................................ 287 Stepping with the Debugger........................................................................................ 288 Demo: Stepping with the Debugger........................................................................... 289 Call Stack and Call Hierarchy..................................................................................... 290 Multiple-Project Solution Demo................................................................................. 291 Adding a Reference..................................................................................................... 292 Project Dependencies.................................................................................................. 293 Startup Project............................................................................................................. 294 Hidden Files ................................................................................................................ 295 Summary ..................................................................................................................... 296

Appendix B Language Integrated Query (LINQ)................................................... 297 Language-Integrated Query (LINQ) ........................................................................... 299 LINQ Example............................................................................................................ 300 Using IEnumerable<T> .............................................................................................. 301 Basic LINQ Query Operators ..................................................................................... 302 Obtaining a Data Source ............................................................................................. 303 LINQ Query Example................................................................................................. 304 Filtering....................................................................................................................... 305 Ordering ...................................................................................................................... 306 Aggregation................................................................................................................. 307 Obtaining Lists and Arrays ......................................................................................... 308 Deferred Execution ..................................................................................................... 309 Summary ..................................................................................................................... 310

Appendix C Unsafe Code and Pointers in C#.......................................................... 311 Unsafe Code................................................................................................................ 313 Unsafe Blocks ............................................................................................................. 314

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 11: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC xi All Rights Reserved

Unsafe Option in Visual Studio .................................................................................. 316 Pointers ....................................................................................................................... 317 Swapping Via Pointers................................................................................................ 319 Fixed Memory............................................................................................................. 320 Fixed Memory Illustration .......................................................................................... 321 Summary ..................................................................................................................... 323

Appendix D Learning Resources .............................................................................. 325

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 12: 4102 Chap01 47 - itcourseware.com

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC xii All Rights Reserved

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 13: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

.NET: What You Need to Know

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 14: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 2 All Rights Reserved

.NET: What You Need to Know

Objectives

After completing this unit you will be able to:

Describe the essentials of creating and running a program in the .NET environment.

Build and run a simple C# program.

Use the ILDASM tool to view intermediate language.

Use Visual Studio 2015 as an effective environment for creating C# programs.

Use the .NET Framework SDK documentation.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 15: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 3 All Rights Reserved

Getting Started

From a programmer’s perspective, a beautiful thing about .NET is that you scarcely need to know anything about it to start writing programs for the .NET environment.

You write a program in a high-level language (such as C#), a compiler creates an executable .EXE file (called an assembly), and you run that .EXE file.

Even very simple programs, if they are designed to do something interesting, such as perform output, will require that the program employ the services of library code.

A large library, called the .NET Framework Class Library, comes with .NET, and you can use all of the services of this library in your programs.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 16: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 4 All Rights Reserved

.NET: What Is Really Happening

The assembly that is created does not contain executable code, but, rather, code in Intermediate Language, or IL (sometimes called Microsoft Intermediate Language, or MSIL).

In the Windows environment, this IL code is packaged up in a standard portable executable (PE) file format, so you will see the familiar .EXE extension (or, if you are building a component, the .DLL extension).

You can view an assembly using the ILDASM tool.

When you run the .EXE, a special runtime environment (the Common Language Runtime, or CLR) is launched and the IL instructions are executed by the CLR.

Unlike some runtimes, where the IL would be interpreted each time it is executed, the CLR comes with a just-in-time (JIT) compiler, which translates the IL to native machine code the first time it is encountered.

On subsequent calls, the code segment runs as native code.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 17: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 5 All Rights Reserved

.NET Programming in a Nutshell

1. Write your program in a high-level .NET language, such as C#.

2. Compile your program into IL.

3. Run your IL program, which will launch the CLR to execute your IL, using its JIT to translate your program to native code as it executes.

We will look at a simple example of a C# program, and run it under .NET.

Don’t worry about the syntax of C#, which we will start discussing in the next chapter.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 18: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 6 All Rights Reserved

.NET Program Example

See SimpleCalc in the Chap01 folder.

1. Enter the program in a text editor.

// SimpleCalc.cs // // This program does a simple calculation: // calculate area of a rectangle public class SimpleCalc { static void Main() { int width = 20; int height = 5; int area; area = width * height; System.Console.WriteLine("area = {0}", area); } } 2. Compile the program at the command-line. Start the console

window via Start | All Programs | Visual Studio 2015 | Visual Studio Tools | Developer Command Prompt for VS2015. Navigate to folder \OIC\CsEss\Chap01\SimpleCalc.

>csc SimpleCalc.cs 3. Run your IL program SimpleCalc.exe

>SimpleCalc area = 100

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 19: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 7 All Rights Reserved

Viewing the Assembly

You can view the assembly using the ILDASM tool1.

>ildasm SimpleCalc.exe

1 You can change the font size from the View menu.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 20: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 8 All Rights Reserved

Viewing Intermediate Language

Double-click on Main:void()

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 21: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 9 All Rights Reserved

Understanding .NET

The nice thing about a high-level programming language is that you usually do not need to be concerned with the platform on which the program executes.

You can work with the abstractions provided by the language and with functions provided by libraries.

Your appreciation of the C# programming language and its potential for creating great applications will be richer if you have a general understanding of .NET.

After this course, we suggest you next study:

Test-Driven Development (Unit Testing)

.NET Framework Using C#

And then, depending on your interests:

Data Access Windows Web

ADO.NET

Windows Forms ASP.NET

XML Programming

WPF ASP.NET MVC

WCF

ASP.NET AJAX

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 22: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 10 All Rights Reserved

Visual Studio 2015

While it is possible to write C# programs using any text editor, and compile them with the command-line compiler, it is very tedious to program that way.

An IDE makes the process of writing software much easier.

An IDE provides convenience items, such as a syntax-highlighting editor.

An IDE reduces the tedium of keeping track of configurations, environment settings and file organizations.

You may use Visual Studio 2015 throughout this course to create and compile your C# programs.

Visual Studio 2015 is discussed in more detail in Appendix A.

In this course you may use any version of VS 2015, including the free Community Edition.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 23: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 11 All Rights Reserved

Visual Studio Sign In

When you first bring up Visual Studio on a new device, you will be invited to sign in.

Sign in with any Microsoft ID.

By doing so you will synchronize your settings among devices and connect to online developer services.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 24: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 12 All Rights Reserved

Creating a Console Application

We will now create a simple console application using Visual Studio.

Our program is the same simple calculator we created earlier that was compiled at the command line.

1. From the Visual Studio main menu, choose File | New | Project.... This will bring up the New Project dialog.

2. Choose Visual C# and “Console Application”.

3. Leave checked “Create directory for solution”. 2

4. In the Name field, type SimpleCalcVs and for Location browse to C:\OIC\CsEss\Demos. Click OK.

2 Examples in later chapters frequently do not have a directory for solution.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 25: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 13 All Rights Reserved

Adding a C# File

There will be a number of starter files. Expand properties and select the files AssemblyInfo.cs (in the Properties folder), App.config and Program.cs. Press the Delete key.

We are now going to add a file SimpleCalc.cs, which contains the text of our program.

1. In Solution Explorer, right click over SimpleCalcVs and choose Add | New Item.... This will bring up the Add New Item dialog.

2. In the middle pane, choose “Code File.” For Name type SimpleCalc.cs. Click Add.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 26: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 14 All Rights Reserved

Using the Visual Studio Text Editor

The empty file SimpleCalc.cs will now be open in the Visual Studio text editor. Enter the following program.

Or you could just copy from Chap01\SimpleCalc\.

// SimpleCalc.cs // // This program does a simple calculation: // calculate area of a rectangle public class SimpleCalc { static void Main() { int width = 20; int height = 5; int area; area = width * height; System.Console.WriteLine("area = {0}", area); } }

Notice that the Visual Studio text editor highlights syntax, indents automatically, and so on.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 27: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 15 All Rights Reserved

IntelliSense

A powerful feature of Visual Studio is IntelliSense.

IntelliSense will automatically pop up a list box allowing you to easily insert language elements directly into your code.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 28: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 16 All Rights Reserved

Build and Run the Project

Building a project means compiling the individual source files and linking them together with any library files to create an IL executable .EXE file.

You can build the project by using one of the following:

Menu Build | Build Solution or toolbar button or keyboard shortcut Ctrl+Shift+B.

Menu Build | Build SimpleCalcVs or toolbar button (this just builds the project SimpleCalcVs)3.

You can run the program without the debugger by using one of the following:

Menu Debug | Start Without Debugging

Toolbar button (This button is not provided by default; see Appendix A for how to add it to your Build toolbar.)

Keyboard shortcut Ctrl + F5

You can run the program in the debugger by using one of the following:

Menu Debug | Start Debugging

Toolbar button

Keyboard shortcut F5.

3 The two are the same in this case, because the solution has only one project, but some solutions have multiple projects, and then there is a difference.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 29: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 17 All Rights Reserved

Pausing the Output

If you run the program in the debugger from Visual Studio, you will notice that the output window automatically closes on program termination.

To keep the window open, you may prompt the user for some input.

public class SimpleCalc { static void Main() { int width = 20; int height = 5; int area; area = width * height; System.Console.WriteLine("area = {0}", area); System.Console.WriteLine( "Prese Enter to exit"); System.Console.ReadLine(); } }

This program is saved as a Visual Studio solution in Chap01\SimpleCalcVs.

Remember that you can always make the console window stay open by running without the debugger via Ctrl + F5.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 30: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 18 All Rights Reserved

Visual C# and GUI Programs

Microsoft’s implementation of the C# language, Visual C#, works very effectively in a GUI environment.

Using Windows Forms, it is easy to create Windows GUI programs in C#.

Example: See Chap01\SimpleCalcGui

We will discuss GUI programming using C# in Chapter 6.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 31: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 19 All Rights Reserved

.NET Documentation

.NET Framework documentation is available online.

Use the menu Help | View Help. Other menu choices let you add and remove content and to set a preference for launching in Browser or Help Viewer.

The .NET Framework 4.5 documentation now includes documentation for .NET 4.6, which is the version of the .NET Framework that comes with Visual Studio 2015.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 32: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 1

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 20 All Rights Reserved

Summary

As in other environments, with .NET you write a program in a high-level language, compile to an executable (.EXE file), and run that .EXE file.

The .EXE file, called an assembly, contains Intermediate Language instructions.

You can view an assembly through the ILDASM tool.

Visual Studio 2015 is a powerful IDE that makes it easy to develop C# programs.

With Visual Studio it is easy to create GUI programs using C#.

You can access extensive .NET Framework documentation through the Visual Studio help system.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 33: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 191 All Rights Reserved

Chapter 5

Delegates and Events

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 34: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 192 All Rights Reserved

Delegates and Events

Objectives

After completing this unit you will be able to:

Use delegate objects to implement callbacks.

Use the Random class to generate random test data.

Describe the use of anonymous methods with delegates.

Use aggregations of delegate objects.

Use lambda expressions as a more concise way to author anonymous methods, simplifying how you can work with delegates.

Use delegate objects to implement and handle event notifications.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 35: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 193 All Rights Reserved

Overview of Delegates and Events

In the previous chapters we examined interfaces in some detail.

One feature of interfaces is that they facilitate writing code in such a way that your program is called into by some other code.

This style of programming has been available for a long time, under the guise of “callback” functions.

In this chapter, we examine delegates in C#, which can be thought of as type-safe and object-oriented callback functions.

Delegates are the foundation for a more elaborate callback protocol, known as events.

Events are a cornerstone of COM, the predecessor of .NET, and are widely used in Windows programming.

We will study events and look at several example programs that illustrate delegates and events.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 36: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 194 All Rights Reserved

Callbacks and Delegates

A callback function is one that your program specifies and registers in some way. This function is then called by another program.

In C and C++, callback functions are implemented using function pointers.

In C#, you can encapsulate a reference to a method inside a delegate object.

While a function pointer can reference only a static function, a delegate can refer to either a static method or an instance method.

When a delegate refers to an instance method, it stores both an object instance and an entry point to the instance method.

The instance method can then be called through this object instance.

When a delegate object refers to a static method, it stores just the entry point of this static method.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 37: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 195 All Rights Reserved

Usage of Delegates

You can then pass this delegate object to other code, which can then call your method.

The code that calls your delegate method does not have to know at compile time which method is being called; it only has to know the exact signature.

In C#, a delegate is considered a reference type that is similar to a class type.

A new delegate instance is created just like any other class instance, using the new operator.

C# delegates are implemented by the .NET Framework class library as a class, derived ultimately from System.Delegate.

Delegates are object-oriented and type-safe, and they enjoy the safety of the managed code execution environment.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 38: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 196 All Rights Reserved

Declaring a Delegate

You declare a delegate in C# using a special notation with the keyword delegate and the signature of the encapsulated method.

delegate bool Compare(int x, int y);

The Compare delegate in this example can contain a reference to any function with the return type bool and two parameters of type int.

An example program illustrates sorting an array in both ascending and descending order.

The choice is made according to what Compare delegate instance is used

See the example program DelegateDemo.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 39: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 197 All Rights Reserved

Defining a Method

When you instantiate a delegate, you will need to specify a method, which must match the signature in the delegate declaration.

The method may be either a static method or an instance method.

Here are some examples of methods that can be hooked to the Compare delegate:

// named methods private static bool LessThan(int x, int y) { if (x < y) return true; else return false; } private static bool GreaterThan(int x, int y) { if (x > y) return true; else return false; }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 40: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 198 All Rights Reserved

Creating a Delegate Object

You instantiate a delegate object with the new operator, just as you would with any other class.

The following code illustrates creating a delegate object that is hooked to a static method.

private static void Ascending() { int[] array = GetArray(); // Instantiate delegate for ascending sort Compare comp = new Compare(GreaterThan); BubbleSort(array, comp); ShowArray(array); }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 41: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 199 All Rights Reserved

Calling a Delegate

You call a delegate just as you would a method.

The delegate object is not a method, but it has an encapsulated method.

The delegate object “delegates” the call to this encapsulated method, hence the name “delegate.”

In the following code, the delegate object comp is called is called to perform a comparison of two elements while performing a sort.

private static void BubbleSort(int[] array, Compare comp) { for (int i = array.Length - 1; i >= 0; i--) { for (int j = 0; j < i; j++) { if (comp(array[j], array[j + 1])) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } }

To conveniently create test data for our example program, let’s see how to generate random numbers in the .NET Framework.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 42: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 200 All Rights Reserved

Random Number Generation

The .NET Framework provides a useful class Random, in the System namespace, which can be used for generating psuedo-random numbers for simulations.

They are called “pseudo-random” because, although they appear random, they are generated deterministically.

There are two constructors:

public Random() // uses default seed public Random(int seed) // seed is specified

The default seed is based on the current date and time, resulting in a different stream of random numbers each time.

By specifying a seed, you can produce a deterministic stream.

Overloaded Next methods produce a random integer.

int volume = rangen.Next(1, 10) * 100;

This code produces a random volume between 100 and 1000, in multiples of 100.

The NextDouble method produces a random double between 0 and 1.

double r = rangen.NextDouble();

The value r is in the range:

0 <= r < 1

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 43: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 201 All Rights Reserved

A Random Array

Our program DelegateDemo generates a random array of integer test data.

using System; class DelegateDemo { private static int[] array; public static void Main() { InitArray(); ShowArray(GetArray()); Ascending(); Descending(); } private static void InitArray() { Random rand = new Random(); // Random size between 5 and 10 int size = rand.Next(5, 10); array = new int[size]; for (int i = 0; i < size; i++) { // Random integers between 1 and 100 array[i] = rand.Next(1, 100); } } ...

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 44: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 202 All Rights Reserved

Anonymous Methods

In .NET 1.0 delegates were defined using named methods.

The example program DelegateDemo provided methods LessThan() and GreaterThan() for hooking to the Compare delegate.

.NET 2.0 provides an alternative means of defining delegates.

It is called anonymous methods.

When you instantiate a delegate, you use a code block inline in place of a named method defined elsewhere in your code.

As an example, consider the program Anonymous.

The same delegate type is declared.

delegate bool Compare(int x, int y);

But now, no named method is defined, but instead when you instantiate a delegate object you use a code block.

// Instantiate delegate for ascending sort // Use anonymous method Compare comp = delegate(int x, int y) { if (x > y) return true; else return false; };

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 45: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 203 All Rights Reserved

Combining Delegate Objects

A powerful feature of delegates is that you can combine them, implementing an invocation list of methods.

When such a delegate is called, all of the methods on the invocation list will be called in turn.

The + operator can be used to combine the invocation methods of two delegate objects and the – operator can be used to remove methods.

The program DelegateAccount illustrates using delegates in our bank account scenario.

The file Account.cs declares the delegate Notify. The Account class has an encapsulated delegate object.

The file DelegateAccount.cs contains methods matching the signature of the delegate.

The Main() method instantiates delegate objects and adds and removes them from the encapsulated delegate object in the Account class.

The Account class uses its encapsulated delegate object to invoke suitable notifications when the account is overdrawn.

The Account class does not know or care which notification methods will be invoked in the case of an overdraft.

It simply calls the delegate, which in turn calls all the methods on its invocation list.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 46: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 204 All Rights Reserved

Account.cs

// Account.cs public delegate void Notify(decimal balance); public class Account { private decimal balance; public Notify notifyDlg; public Account(decimal bal) { balance = bal; } public void Deposit(decimal amount) { balance += amount; } public void Withdraw(decimal amount) { balance -= amount; if (balance < 0) notifyDlg(balance); } }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 47: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 205 All Rights Reserved

DelegateAccount.cs

using System; public class DelegateAccount { public static void Main(string[] args) { Account acc = new Account(100); Notify custDlg = new Notify(NotifyCustomer); Notify bankDlg = new Notify(NotifyBank); // Notify customer of an overdraft acc.notifyDlg += custDlg; acc.Withdraw(125); // Also notify bank of an overdraft acc.notifyDlg += bankDlg; acc.Withdraw(50); // Remove bank notification acc.notifyDlg -= bankDlg; acc.Withdraw(50); } private static void NotifyCustomer( decimal balance) { Console.WriteLine("Dear customer,"); Console.WriteLine( " Account overdrawn, balance = {0}", balance); } private static void NotifyBank(decimal balance) { Console.WriteLine("Dear bank,"); Console.WriteLine( " Account overdrawn, balance = {0}", balance); } }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 48: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 206 All Rights Reserved

Lambda Expressions

A lambda expression is an anonymous function using the lambda operation =>, which is read “goes to.”

The left side specifies any input parameters.

The right side holds an expression or statement block.

A lambda expression can be used to create a delegate.

Here is a delegate:

delegate int Calculate(int x);

Here is a method that makes use of the delegate:

static void Show5(Calculate calc) { for (int i = 1; i <= 5; i++) Console.WriteLine("{0} {1}", i, calc(i)); }

Here is a lambda expression that creates the delegate anonymously.

Show5(x => x * x);

The result is a table of squares of the first five integers.

1 1 2 4 3 9 4 16 5 25

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 49: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 207 All Rights Reserved

Named Method

To better understand this example, let’s review how it would be expressed using a named method, as in the original .NET 1.0.

See NamedMethod.

class Program { delegate int Calculate(int x); static void Show5(Calculate calc) { for (int i = 1; i <= 5; i++) Console.WriteLine("{0} {1}", i, calc(i)); } static int Square(int x) { return x * x; } static void Main(string[] args) { Calculate dlgSquare = new Calculate(Square); Show5(dlgSquare); } }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 50: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 208 All Rights Reserved

Anonymous Method

Next, let’s see how it would be expressed using an anonymous method, as in.NET 2.0.

See AnonymousMethod.

class Program { delegate int Calculate(int x); static void Show5(Calculate calc) { for (int i = 1; i <= 5; i++) Console.WriteLine("{0} {1}", i, calc(i)); } static void Main(string[] args) { Calculate dlgSquare = delegate(int x) { return x * x; }; Show5(dlgSquare); } }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 51: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 209 All Rights Reserved

Lambda Expression Example

Finally, let’s look at the same functionality using a lambda expression. Our example also illustrates explicitly typing the input parameter and using multiple statements.

See SimpleLambda.

class Program { delegate int Calculate(int x); static void Show5(Calculate calc) { for (int i = 1; i <= 5; i++) Console.WriteLine("{0} {1}", i, calc(i)); } static void Main(string[] args) { // inferred type Show5(x => x * x); // explicit type Show5((int x) => x * x * x); // multiple statements Show5((int x) => { if (x % 2 == 0) return x * x; else return x * x * x; }); } }

The third lambda will show squares of even numbers and cubes of odd numbers.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 52: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 210 All Rights Reserved

Events

Delegates are the foundation for a more elaborate callback protocol known as events.

Conceptually, servers implement incoming interfaces, which are called by clients.

In a diagram, such an interface may be shown with a small bubble (a notation used in COM).

Sometimes a client may wish to receive notifications from a server when certain events occur.

The server may then specify an outgoing interface.

The server defines the interface and the client implements it.

In a diagram, such an interface may be shown with an arrow (again, a notation used in COM).

ServerClient

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 53: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 211 All Rights Reserved

Events in C# and .NET

The .NET event architecture uses delegates of a specific signature:

public delegate void JoinHandler( object sender, ChatEventArg e);

The first parameter specifies the object that sent the event notification.

The second parameter is used to pass data along with the notification. Typically, you will derive a class from EventArg to hold your specific data.

public class ChatEventArg : EventArgs { public string Name; public ChatEventArg(string name) { Name = name; } }

A delegate object reference is declared using the keyword event.

public event JoinHandler Join;

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 54: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 212 All Rights Reserved

Events in C# and .NET (Cont’d)

A helper method is typically provided to facilitate calling the delegate object(s) that have been hooked up to the event.

protected void OnJoin(ChatEventArg e) { if (Join != null) { Join(this, e); } }

A test for null is made in case no delegate objects have been hooked up to the event.

Typically, access is specified as protected, so that a derived class has access to this helper method.

You can then fire the event by calling the helper method.

public void JoinChat(string name) { members.Add(name); OnJoin(new ChatEventArg(name)); }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 55: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 213 All Rights Reserved

Client Side Event Code

The client provides event handler functions.

public static void OnJoinChat(object sender, ChatEventArg e) { Console.WriteLine( "sender = {0}, {1} has joined the chat", sender, e.Name); }

The client hooks the handler to the event, using the += operator.

ChatServer chat = new ChatServer("MSN Chat Room"); // Register to receive event notifications from the // server chat.Join += new JoinHandler(OnJoinChat);

The event starts out as null and event handlers get added through +=.

All of the registered handlers will get called.

You may unregister a handler through -=.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 56: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 214 All Rights Reserved

Chat Room Example

A chat room example illustrates the complete architecture on both the server and client side.

See EventDemo\Step2.

The server provides the following methods:

JoinChat

QuitChat

ShowMembers

Whenever a new member joins or quits, the server sends a notification to the client.

sender = MSN Chat Room, Michael has joined the chat sender = MSN Chat Room, Bob has joined the chat sender = MSN Chat Room, Sam has joined the chat --- After 3 have joined--- Michael Bob Sam sender = MSN Chat Room, Bob has quit the chat --- After 1 has quit--- Michael Sam

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 57: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 215 All Rights Reserved

Lab 5

Implementing Events

In this lab, you will study the chat room server and add code to the chat room client in order to provide event handlers and hook them to the event. You will also add code to the server in order to provide better information about the sender of the event.

Detailed instructions are contained in the Lab 5 write-up at the end of the chapter.

Suggested time: 20 minutes

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 58: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 216 All Rights Reserved

Summary

Delegates can be thought of as type-safe and object-oriented callback functions.

In C#, you can encapsulate a reference to a method inside a delegate object.

You can then pass this delegate object to other code, which can call your method.

The code that calls your delegate method does not have to know at compile time which method is being called.

Delegates can be defined using named methods, with anonymous code defined inline, or via lambda expressions.

Delegates can be combined, creating an invocation list of methods.

The Random class, in the System namespace, provides an easy means for generating random numbers.

Delegates are the foundation for a more elaborate callback protocol, known as events.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 59: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 217 All Rights Reserved

Lab 5

Implementing Events

Introduction In this lab, you will study the chat room server and add code to the chat room client to provide event handlers and hook them to the event. You will also add code to the server to provide better information about the sender of the event. Suggested Time: 20 minutes Root Directory: OIC\CsEss Directories: Labs\Lab5\EventDemo (do your work here) Chap05\EventDemo\Step0 (backup copy of starter files) Chap05\EventDemo\Step1 (answer to first part) Chap05\EventDemo\Step2 (final answer) Instructions 1. Build and run the starter project. You will see a printout showing chat room

membership after three people have joined and again after one person has quit. Study the code in both the server and client. The server is fully provided with event functionality. No events are fired, because no client has hooked into any of the events.

2. In the client, add event handlers OnJoinChat and OnQuitChat with the proper signature for event handlers. They should print out the sender and also a brief message indicating who has joined or quit the chat.

3. In the Main method, add code to register these event handlers with the appropriate server events.

4. Build and run the program. You should now see that your event handlers are called every time someone joins or quits the chat. But the information about the sender is not very descriptive – just the name of the class of the sender is displayed. (Step 1)

5. To get more descriptive information, add a field chatName to the ChatServer class that is initialized in the constructor. Add code in the client to provide a chat name when instantiating a ChatServer object.

6. Now add code to the server so that the chat name will be displayed, rather than the class name, when the client prints out the sender. How do you do this?

7. You do it by overriding the ToString method. Build and run. (Step 2)

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

Page 60: 4102 Chap01 47 - itcourseware.com

CsEss Chapter 5

Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 218 All Rights Reserved

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited