Course 419 C# Programming

G419/CN/E.1/609/D.1 © LEARNING TREE INTERNATIONAL, INC. All rights reserved.

All trademarked product and company names are the property of their respective trademark holders.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, or translated into any language, without the prior written permission of the publisher.

Copying software used in this course is prohibited without the express permission of Learning Tree International, Inc. Making unauthorized copies of such software violates federal copyright law, which includes both civil and criminal penalties.

Introduction and Overview Course Objectives

 In this course, we will discuss the syntax and semantics of C# as • An object-oriented language ◦ Using encapsulation, inheritance, interfaces, realization, polymorphism, associations, and aggregates • A component-oriented language focusing on reuse via the .NET Framework Library, including ◦ Desktop graphical and web-based user interfaces ◦ Enabling cross-language operation ◦ Performing I/O using serial streams and serialization ◦ Interfacing to legacy COM components • A data-oriented language ◦ Using LINQ and the

COM = component object model I/O = input/output LINQ = Language Integrated Query

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. Intro-2 Course Contents

Introduction and Overview Chapter 1 Overview and Development Environment Chapter 2 From Your Language to C# Chapter 3 User Interface Development Chapter 4 Defining User-Written Data Types Chapter 5 The .NET Framework Chapter 6 Interfaces and Polymorphism Chapter 7 Writing .NET Components Chapter 8 Accessing Databases Chapter 9 Other C# Features Chapter 10 Course Summary Next Steps

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. Intro-3 Course Contents

Appendix A Performance Tips Appendix B Unsafe Features Appendix C Other C# Features

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. Intro-4 Prerequisites

 Although this course is an introduction to C#, it is intended for experienced programmers • A background in a modern procedural language is needed ◦ For example: C/C++, Java, VB, VB.NET, Pascal • You will need to be comfortably familiar with concepts such as ◦ Data types, variables, declarations, conditionals, loops, expressions, functions, parameter passing, and procedural language flow  Course 502, Programming With .NET Introduction, is recommended if you have only • HTML or SQL experience • Experience in languages like COBOL, RPG, PL/SQL, T-SQL  Some modest exposure to object-oriented concepts is also assumed Please notify your instructor if you do not meet the prerequisites

COBOL = common business-oriented language SQL = structured query language HTML = hypertext markup language T-SQL = Transact-SQL PL/SQL = procedural language/structured query language VB = Visual Basic

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. Intro-5 Course Fonts and Icons

 These fonts and symbols have special meaning in the Course Notes: • Text in Century Schoolbook italic introduces a new concept or term • Text in Courier bold is C# code keywords or command text • Text in plain Courier is program output or C# code • Text in Courier italic is nonliteral code or command text

Slippery When Wet Question Potentially confusing or variance from Question for the attendee common use in other languages Surfer Warning Additional information can be found Feature that if used incorrectly can lead to at this web reference problems Version n Crystal Ball This feature is available only in C# Reference to material that will be discussed version n or later. For example, the later note below would indicate that the Good Idea capability discussed requires at least C# V6 Feature to make programs easier to write or maintain

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. Intro-6 Chapter 1

Overview and Development Environment Chapter Objectives

In this chapter, we will examine  A brief history of C#  Some elementary features of the language  How to use our development tools

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-2 Chapter Contents

 Evolution From C to C#

• Development Environment

• Hands-On Exercise 1.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-3 Differences and Similarities

 C# has borrowed many concepts and constructs from other languages • In particular, C++, Java, VB, and SQL  Depending on your background, some aspects of C# might seem the same as a language you have previously used, but … Don’t be fooled! • In the midst of the familiar, there will often be some unexpected differences  The course is written with these differences and similarities in mind

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-4 C-Style Syntax

 It all started with C • Dennis Ritchie at Bell Labs in 1971 • The language of choice on UNIX and PCs in the 1970s and 1980s ◦ Still widely used  C introduced what is now called C-style syntax • Each statement ends in a semicolon (;) • Code blocks (body) are enclosed between { and } • Uppercase and lowercase are distinct • Function-oriented; e.g., main and printf

#include int main(void) { printf("Hello world!\n"); return 0; }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-5 C-Style Syntax

 C-style syntax is free-format • Input is broken into tokens by the compiler • The order of the tokens is important, but not their column positions  For example, these programs are semantically identical: int int main(void) main( void { ) { printf printf("Hello World\n"); ( return 0; "Hello World\n") } ; return 0; }

int main(void) {printf("Hello World\n"); return 0;}

Good engineering practice suggests adopting a clear, properly indented, consistent coding style • This course demonstrates the generally accepted coding style

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-6 Evolution From C

 The C language eventually evolved into other languages with similar syntax, such as C++ • Which added object orientation … and then Java • Which was more portable and easier to program than C++ ◦ But with reduced performance … and then JavaScript (JScript) • For scripting and web niches … and then …

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-7 C# History

 C# appeared in 2001 as the “first 21st-century language” • Developed by Microsoft for its .NET initiative • Follows the C/C++/Java trend ◦ But also borrows from Visual Basic, Smalltalk, Lisp, and others  Designed to be • Easier to write and much less error-prone than C++ • More efficient with better performance than Java • Multimission—to be used for virtually any kind of application • Multilayer—to be the language of choice in any application layer  C# is • Object-Oriented (OO), supporting all modern OO concepts • Component-Oriented (CO), with CO features built into the language • Data-oriented, with SQL-like data-manipulation built into the language ◦ Called Language INtegrated Query (LINQ)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-8 C# Versions and Standards

 C# is not Microsoft’s language per se • Standardized through ECMA and ISO/IEC  Microsoft version is called Visual C# .NET ® • February 2002: V1—pre-standard version had most language features • November 2005: V2—fully compliant with 23270 1st edition • December 2007: V3—fully compliant with ECMA-344 4th edition • April 2010: V4—fully compliant, adds extended features • August 2012: V5—fully compliant, adds extended features • July 2015: V6—fully compliant, adds numerous small, very useful features

ECMA = European Computer Manufacturers Association ISO = International Organization for IEC = International Electrotechnical Commission Standardization

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-9 Hello World in C#

 Here is the “Hello World” program in C#:

using System; public class HelloWorld { public static int Main() { Console.Write("Hello world!\n"); return 0; } }

 Syntax is similar and output is identical to previous C program • Main method (function) is in a class • Uses Console.Write method from the .NET framework library • Otherwise, it has mostly the same tokens and keywords

C:\Course\419\Samples\HelloWorldExample

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-10 Comments

 In a C# program, only comments are not tokenized • Considered whitespace by the compiler  There are three different styles • Multiline starts with /* and ends with */ • Single-line starts with // and finishes at the end of the line • XML-based documentation uses ///

///

/// This will be included in the documentation and IntelliSense ///

public static int Main() { /* This style of comment can go over over multiple lines. */

int i = 100; // This style goes to the end of the line. }

XML = extensible markup language

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-11 Chapter Contents

• Evolution From C to C#  Development Environment

• Hands-On Exercise 1.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-12 .NET Architecture Overview

 The overall architecture of .NET is built on well-organized logical layers • With development supported through Visual Studio

C# VB.NET C++/CLI F# Many Others…

Common Intermediate Language (CIL) Visual Studio Visual

Application frameworks (ASP, WPF, WSA etc.)

Class libraries (I/O, utility classes)

Communication, database, and entity frameworks (EF, WCF)

Deployment—Assembly component model

Any operatingCommon system, Language database, Infrastructure compact device, (CLI) or SOA

ASP = Active Server Pages EF = Entity Framework WCF = Windows Communication Foundation WPF = Windows Presentation Foundation WSA = Windows Store Apps (metro)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-13 Visual Studio Overview

 Visual Studio® is the “mother ship” for .NET and C# development • Various flavors—Community (free), Professional, etc. • See www.microsoft.com  Visual Studio 2015 Professional has been installed • All modules have been installed; they include: ◦ SQL Server 2012 ◦ C# V6 ◦ .NET Frameworks through version 4.6.1 Many exercises can be done using earlier versions of Visual Studio • Unless a language or library feature is not supported in that version • Usually requires that new projects be created in your Visual Studio instance ◦ Then use Add | Existing Item to include the course exercise files • The Course Notes use a tag to indicate which version of C# is needed indicates, for example, C# V4

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-14 Visual Studio Solutions and Projects

 A solution in Visual Studio is the total application (.sln) • Possibly many projects  A project is a collection of files that are developed together for some cohesive reason • A component class library (.dll) • Might be an executable (.exe)  The same project can be included in different solutions In the Exercise Manual, “Open the solution for …” refers to the Visual Studio solution, not the completed exercise answers

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-15 Managed Code

 C# compilers generate • Common Intermediate Language (CIL) • Metadata describing the contents of the .exe or .dll file produced ◦ No “include files” or “copy books” needed  Just-In-Time (JIT) translator creates native binary when the program is executed (or optionally when installed) • You will not likely notice this translation step!  To run a .NET program, the Common Language Infrastructure (CLI) must be installed to “manage” the execution process • Microsoft’s version is called the (CLR) • Automatically installed on most Windows platforms  Native binary and the CLI are placed in folders under a system-specific directory that includes the Global Assembly Cache (GAC) • C:\Windows\Microsoft.NET\Assembly on our course load

DLL = dynamic link library

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-16 Managed Code

 The compilation and runtime environment

CIL and metadata in C# source files .dll or .exe files (extension .cs)

{ { C# C JIT } 11010 } compiler 10011 translator 10011

Native Solution and project Native CLI control files (extensions binary .sln and .csproj)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-17 Common Language Infrastructure

 .NET programs are executed within and are managed by the CLI, not directly under the native operating system  The CLI provides most runtime services, including • Cross-language integration • Garbage collection • Simple component access and interaction • Database connection and communication • Other typical runtime support  There are CLI implementations and C# compilers for many platforms • Windows implementation is called the Common Language Runtime (CLR) • Most popular UNIX/Linux implementation is from the -Project (MPCLI)  —cross-platform C# development • Support for Android, iPhone/iPad and Windows/Windows Phone from a single source set • Now owned by Microsoft (included in VS 2015)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-18 Assemblies

 A single .EXE or .DLL is called an assembly • Sometimes also called a component  It is typical to “assemble all assemblies” in a single directory or directory tree • Often including other related files such as icons and images  DLLs not directly part of our Visual Studio solution must also be copied into that same directory tree • Copied automatically in Visual Studio when we add a “reference”  To deploy a .NET application, simply copy the “assembly of assemblies” to its installed location

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-19 Chapter Contents

• Evolution From C to C#

• Development Environment  Hands-On Exercise 1.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-20 About the Hands-On Exercises

 The exercises are designed to illustrate and reinforce concepts discussed in the Course Notes  The computers you are using have been specifically configured for classroom use • Run in a VMware partition that can be quickly reloaded • Have various software tools and database servers pre-installed  The best experience will be obtained by using the computers provided • Please do not use personal laptops during the course  Most exercises have bonus sections • You can do them if you finish the core exercise early • Not everyone will have time to do all of the bonus exercises

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-21 Exercise Operating System

 For your exercises, you will be using Windows 7 Enterprise (32-bit)  It runs under VMware hosted on Windows 7 (64-bit) • Virtual machines are used to simplify loading of classroom computers Had we not mentioned it, you might not have noticed; however … • If the desktop color you see is black or is showing a picture of “grass,” you are looking at the host system, not your working environment ◦ The desktop background of your working environment is dark blue • Please tell your instructor if your desktop is not dark blue

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-22 Exercise Accounts and Passwords

 The account and password for LogMeIn (online participants) is • Username: User • Password: pw  The account and password for the host operating system is • Username: User • Password: pw  Your account name for your Windows 7 work environment is • Username: Student • Password: studentpw  The system administrator account for SQL Server is • Username: sa • Password: sqlpw All are fully privileged administrator accounts

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-23 Exercise Files

 All course-specific files are located in the directory C:\Course\419 • Other than the operating system and development tools, everything needed for this course will be there  This is also the content available in your My Learning Tree account  Should you decide to do some of the exercises after the course on your own machine, you can place the course folder anywhere you like

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-24 AdaptaLearn™ Enabled

 Electronic, interactive exercise manual  Offers an enhanced learning experience • Some courses provide folded steps that adapt to your skill level • Code is easily copied from the manual • After class, the manual can be accessed remotely for continued reference and practice  Downloaded PDF copies show all detail levels • Hints and answers are unfolded

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-25 Using AdaptaLearn™ Do Now

1. Launch AdaptaLearn by double-clicking its icon on the desktop • Move the AdaptaLearn window to the side of your screen or shrink it to leave room for a work area for your development tools 2. Select an exercise from the exercise menu • Zoom in and out of the AdaptaLearn window • Toggle between the AdaptaLearn window and your other windows 3. Look for a folded area introduced with blue text (not available in all courses) • Click the text to see how folds work 4. Try to copy and paste text from the manual • Some courses have code boxes that make it easy to copy areas of text while highlighted (as shown)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-26 Hands-On Exercise 1.1

In your Exercise Manual, please refer to Hands-On Exercise 1.1: Our Development Environment

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-27 Chapter Contents

• Evolution From C to C#

• Development Environment

• Hands-On Exercise 1.1  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-28 Review Questions

What is output from the Visual Studio C# compiler?

True or false? [ ] Programs written in C# can only run on Windows platforms [ ] The C# standard was approved through ECMA [ ] A Visual Studio solution can contain one or more projects How is a .NET application deployed?

What is managed code and what manages it?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-29 Chapter Summary

In this chapter, we have examined  A brief history of C#  Some elementary features of the language  How to use our development tools

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-30 Chapter 2

From Your Language to C# Chapter Objectives

In this chapter, we will examine  The fundamental differences between C# and other programming languages  Program organization  Data types  Operators and expressions  Strings and arrays  Loops and conditionals  Exceptions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-2 Chapter Contents

 Namespaces and Methods

• Data Types and Literals

• Hands-On Exercise 2.1

• Expressions and Operators

• Arrays and Strings

• Parameter Passing

• Loops and Conditionals

• Hands-On Exercise 2.2

• Exceptions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-3 Program Layout

 Recall the layout of our monetary conversion program:

namespace CurrencyConverter { class Program { static void Main(string[] args) { … statements … System.Console.Write(…); System.Console.WriteLine(…); } static double GetAmount(string prompt) { … statements … } static double Convert(string ic, double d) { … statements … } static char SymbolFor(string currency) { … statements … } } }

C:\Course\419\Exercises-Completed\Ex11

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-4 Declaring a Namespace

 Notice that the overall layout is divided into layers  The outermost layer begins with the line namespace CurrencyConverter • Namespaces are a useful way of grouping programs cohesively • Code in different source files can belong to the same namespace • Use is optional except when developing components ◦ We will use namespaces as a matter of good practice  Namespaces help avoid name clashes • Simplifies deployment • Promotes reuse  Can be arranged hierarchically for multilevel organization • Sub-namespaces are separated by a period, as in System.IO  Namespaces and classes are sometimes used when we call a method, as in System.Console.WriteLine(…); • System is a different namespace • Console is a class within that namespace

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-5 Using Namespace Directives

 This can be further refined using a static directive for the method itself using System; namespace CurrencyConverter Namespace directive here means … { class Program { static void Main(string[] args) … you do not have to { use namespace here … statements … Console.Write(…); Console.WriteLine(…); } … other methods … } }  This is a pleasant convenience • Saves typing and keeps programs from looking cluttered

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-6 Using Static Namespace Directives

 Alternatively, we could have used a namespace directive, as in: using System; using static System.Console; Static directive here means … namespace CurrencyConverter { class Program { … you do not have to static void Main(string[] args) use the class name here { … statements … Write(…); WriteLine(…); } … other methods … } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-7 Method Definition

 Now let’s consider the overall definition of a method  In general, a method definition consists of two parts • A specification (or header or interface) tells how to use the method • A body (or block or implementation) tells what the method does  In our program, Main is defined as:

static void Main(string[] args) Specification { … statements … Body }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-8 Method Specification

 The specification indicates how a method is used and has the format: [Qualifiers] [Return Type] Name([Parameters])

 In this case • The method name is Main • The only qualifier is static ◦ static means accessible at the class level . Without creating an object instance . Note that most methods are not static • The single parameter is (string[] args) ◦ Meaning an “array of strings” is passed to the Main method • The return type is void ◦ void means no data is returned from the method

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-9 Method Signatures

 For methods, the name, in combination with the list of parameters, is called the signature  Identification of a method is done by the signature, not just the name • A different signature means it is a different method • For example, foo(int i) and foo(double d) are different methods ◦ foo(4.52) would call which of these methods?

 This is known as overloading Initially, overloading might seem unnecessary and potentially confusing; later, we will see that it is indispensable and actually makes object-oriented programming cleaner and easier

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-10 Chapter Contents

• Namespaces and Methods  Data Types and Literals

• Hands-On Exercise 2.1

• Expressions and Operators

• Arrays and Strings

• Parameter Passing

• Loops and Conditionals

• Hands-On Exercise 2.2

• Exceptions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-11 Primary Types

 Primary data types are understood directly by the compiler

Type Description V R Comments Other integral types include byte, ulong, int 32-bit signed X short, etc. char 16-bit Unicode X See www.unicode.org

bool true or false X See www.ieee.org double IEEE 64-bit X There is also float (32-bit) type decimal 128 bit X Exact to 28 decimal digits enum N/A X Enumeration of a primary value-type string 16-bit Unicode X Not arrays of characters. Immutable. array N/A X Reference to array of any type object N/A X Base class for all types

V = value type R = reference type

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-12 Value and Reference Variables

 Value means as a variable, the data is stored and MEMORY accessed directly Static • On the stack area  Reference means the data is stored and accessed indirectly Stack • Usually on the heap  For example:

public static void Main() Allocated on { the stack double inAmt, outAmt; Heap string inCur = "USD"; string outCur = "EUR"; … statements … Allocated on } the heap

C:\Course\419\Exercises-Completed\Ex11

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-13 User-Written Types

 Other types available in C# are class and struct types MEMORY • Not predefined in the language • User-written or obtained from a class library  Structures are always value types • Allocated automatically on the stack complex c;

 Classes are always reference types • Usually allocated on the heap with new keyword Account a = new Account();

 An instance of a class or a structure is called an object  Classes are used far more often than structures How to define classes and structures will be discussed later

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-14 Different Memory Allocation Schemes

Initially, having variables with different memory allocation schemes might seem confusing, but … • Both types are used in essentially the same manner ◦ Except for a few notable cases that we will discuss later • Makes C# easier to program

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-15 Numeric Literals

 Integer literals can be written as Base 10 (decimal) or Base 16 (hexadecimal), but not Base 8 (octal) • 123, 0x45AF • Long literals are followed by an L 077 is base 10, not octal!  Floating-point numbers must contain a decimal point or exponent but cannot end in a decimal point • 1.0, 2E5, 1.62e-19 132. is not valid! • float literals are followed by f • decimal literals are followed by m

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-16 Character and String Literals

 Character literals are Unicode characters surrounded by single quotes • 'X' • '\u20AC' is the euro symbol, € • '\n' is a newline • '\\' is backslash  String literals are sequences of Unicode characters enclosed in double quotes • "C:\\new_source\\trip_data.txt"

Using a verbatim character eliminates the need for a double backslash • @"C:\new_source\trip_data.txt"

Watch out! Not all fonts available on a Windows platform support Unicode • Trying to display Unicode strings or characters when the font does not support it can give “peculiar” results To observe the complete Unicode character/hex mapping, run the project in C:\Course\419\Samples\CharacterTestWin

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-17 Chapter Contents

• Namespaces and Methods

• Data Types and Literals  Hands-On Exercise 2.1

• Expressions and Operators

• Arrays and Strings

• Parameter Passing

• Loops and Conditionals

• Hands-On Exercise 2.2

• Exceptions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-18 Hands-On Exercise 2.1

In your Exercise Manual, please refer to Hands-On Exercise 2.1: Methods and Namespaces

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-19 Chapter Contents

• Namespaces and Methods

• Data Types and Literals

• Hands-On Exercise 2.1  Expressions and Operators

• Arrays and Strings

• Parameter Passing

• Loops and Conditionals

• Hands-On Exercise 2.2

• Exceptions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-20 Expressions

 Let’s consider the conversion function from our sample program public static double Convert(string ic, double amt) { const double convRate = 0.7879; double convValue; if (ic == "EUR") convValue = amt / convRate; else convValue = amt * convRate; return convValue; }

 The statement (amt / convRate) is an expression • Like variables and literals, expressions have a type and a value • Can be used directly—i.e., the program could have avoided the intermediate variable convValue by using return amt / convRate;  In the code above, the keyword const means • convRate must be initialized in its definition and you cannot assign anything to it

C:\Course\419\Exercises-Completed\Ex21

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-21 Operators

 The principal C# symbolic operators are:

Operator type Symbols Description Arithmetic + - * / % Typical precedence Assignment = Assignment or initialization Increment ++ -- Adds or subtracts 1 from the operand Equality == != Do not confuse = and == Relational > < >= <= Logical && || ! Bitwise & | ^ ~ Do not confuse && and &, etc. Shift << >> Left and right bit shifting Lambda => Shorthand for a function or method Conditional ?: Inline conditional Nullable ? ?? Specification resolution

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-22 Operators

 For the most part, symbolic operators are consistent with other languages • Usage, precedence, and associativity are similar • Grouping can be modified with parentheses: ( ) Note: Integer division does not round, it truncates • For example, 11/4 gives 2, not 3 (VB gives 3) • Works like VB \ operator  Some arithmetic operators can be combined (shorthand) i += 5 has the same effect as i = i + 5

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-23 Assignment Operator

 When assigning a value type, a copy of the value is MEMORY made  When assigning reference types, a copy of the reference is made

public static void Main() { int i = 5; int j;

j = i;

Account a1 = new Account(); Account a2;

a2 = a1; }

C:\Course\419\Samples\AssignmentAndEquality

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-24 Equality Operator

 When comparing a value type, a comparison of the value is MEMORY made  When comparing a reference type, a comparison of the reference (memory address) is made • Can be modified to be logical (value) equality public static void Main() { int i = 5; int j = 5;

if (i == j) ... // True, values are the same

Account a3 = new Account(125); Account a4 = new Account(125);

if (a3 == a4) ... // Probably false, why? }

C:\Course\419\Samples\AssignmentAndEquality

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-25 Mixed-Type Operations

 C# allows implicit mixed-type operations where doing so will not potentially corrupt data • Implicit conversion from a “smaller” to a “larger” type is generally acceptable ◦ Floating-point types are considered “larger” than integral types  When implicit conversions happen • The value of the “smaller” is temporarily converted to the “bigger” • The result is of the “bigger” type • Conversions are performed subexpression by subexpression  For example:

int i = 5; long n = 4; double x;

x = n * i; // i temporarily converted to long // long result converted to double

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-26 Casting

 When the potential for data corruption exists, a cast must be performed • Usually when going from a “larger” type to a “smaller” type  For example: bool b; char c; int i; long n; double d; decimal x;

c = 97; // error – no implicit conversion c = (char)97; // cast – c becomes a Unicode 'a' i = (int)5.8; // cast – i gets 5 b = i; // error – no conversion from int to bool b = (bool)i; // error – no conversion from int to bool n = i; // ok – implicit conversion small to big d = n; // ok – implicit conversion small to big x = d; // error – no implicit conversion d = x; // error – no implicit conversion d = (double) x; // ok – works the other way around too

C:\Course\419\Samples\Casting

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-27 Casting

Be careful when using casting; think of it as telling the compiler “I know better than you do, so do what I say”—it will! • Assigning a floating-point value to an integer truncates the fraction • Assigning a “big” integer to a “small” integer drops high-order bits

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-28 Casting Do Now

Change our program to use decimal rather than double • Better for handling currency; double is for scientific calculations 1. Launch Visual Studio (VS) and open the solution for the currency converter found in C:\Course\419\Do Now Demo\Do21 2. Change all occurrences of double to decimal using menu Edit | Find and Replace | Quick Replace—make sure you do this only in the “current document”! 3. Try to compile; you will get errors 4. Find the initialization statements and arguments that have errors, and modify their literals to be of type decimal (suffix m) 5. Try to compile again; there will still be some errors because the EuroTable is still returning double results 6. Cast these returned values (decimal) 7. Compile and test; the program should work as before, but is now more accurate

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-29 enums

 C# supports enums of any integral type—int is the default • Do not have to start at 0 or 1 or be sequential  Typically placed in namespace or class scope • Cannot be in method scope as in some other languages  Casting can be used to convert to/from the enum’s basis

public class Banking { public enum CurrencyCode {EUR = 1, USD, CAD, GBP, JPY} public static void Main() What value would ic get? { int ic = (int) CurrencyCode.CAD; CurrencyCode code = CurrencyCode.JPY; int cVal = 4; CurrencyCode cc = (CurrencyCode) cVal; ... } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-30 Chapter Contents

• Namespaces and Methods

• Data Types and Literals

• Hands-On Exercise 2.1

• Expressions and Operators  Arrays and Strings

• Parameter Passing

• Loops and Conditionals

• Hands-On Exercise 2.2

• Exceptions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-31 Arrays

 C# includes support for arrays of any data type • An array is a linear storage of elements accessed by an index  Arrays in C# are allocated dynamically (on the heap) using new int[] ia = new int[100]; // Define array of 100 ints

 Or can be created using an initialization block, as in: int[] primes = {2, 3, 5, 7, 11}; // First 5 prime numbers

 To determine the size of an array, check its Length property int dim = primes.Length; // Would yield 5

 Once allocated, array indexing and usage is typical • For example: ia[2] = 234; // Assign 234 to 3rd element Indexes start at 0, not 1 What happens if you index outside of the array dimensions?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-32 Multidimensional Arrays

 Java-like “arrays-of-arrays” are supported but must be built line by line double[][] matrix = new double[4][]; matrix[0] = new double[8]; matrix[1] = new double[8]; … etc. …

What would matrix.Length yield? How about matrix[1].Length?

 FORTRAN-like “true” multidimensional arrays are also supported int[,] grid = new int[4,8]; grid[2,3] = 22123;

What would grid.Length yield?

C:\Course\419\Samples\ArrayLength

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-33 Strings as Arrays

 A string is not an array of characters in the C/C++ sense, but … • Indexing can be used to obtain (but not put) an individual character string output = "Hello"; char x = output[1]; // Get the 2nd character 'e'

 The number of characters can be obtained using the Length property int charCount = output.Length; // Gives 5

 Strings are immutable, meaning they cannot be changed in place • output.ToUpper(); would not change the original output string ◦ output = output.ToUpper(); would be required

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-34 String Operators

 A string can be concatenated with other strings or with any other data type using the + operator string output = "The answer is " + value;

Strings can be checked for equality of value using the == and != operators string answer = "yes"; if (answer == "yes")

 Comparison using relational operators, such as < or >=, is not supported

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-35 Named Operations

 In addition to the symbolic operators we have been discussing, most data types also have named operations • These are actually methods  Can be accessed using the “.” operator  string has numerous named operations for string manipulation • For example, the following will obtain 1 character starting at index 8:

string productID = "ALA1554-D"; string revision = productID.Substring(8,1);

C:\Course\419\Samples\Substring

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-36 String Formatting

 The string class has methods for formatting • Which is also used by the System.Console.WriteLine method  For example double x = 9924.567; string fs = string.Format("Balance = ${0:N2}",x);  Will produce the formatted string “Balance = $9,924.57”  Other format specifiers are available • C, currency: “locale” dependent • D, decimal: converts output to integer format • E, exponential: scientific format • F, fixed point: accuracy is after decimal point • G, general: accuracy is total number of digits • N, numeric: similar to F but with separation in the thousands

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-37 Output Formatting

 Field width and justification can also be specified string fs = string.Format("{0,-5}", data);

• A left-justified field that is five characters wide  Width and formatting can be combined and used directly in I/O Console.WriteLine(">{0,12:F3}<", 7127.132956);

What output would the preceding code produce?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-38 String Interpolation

 A short form for string formatting can be done by interpolation  Note the $ and { and } in the syntax

string productID = "ALA1554"; string productName = "Super Thing"; ... WriteLine($"{productID} is a {productName}.";

What output would this produce?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-39 Data Conversion

 Many data types have the ability to parse a string into their type  For example:

string input = "12345"; int i = int.Parse(input);

• Parses a string into an integer

C:\Course\419\Samples\Parse

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-40 Chapter Contents

• Namespaces and Methods

• Data Types and Literals

• Hands-On Exercise 2.1

• Expressions and Operators

• Arrays and Strings  Parameter Passing

• Loops and Conditionals

• Hands-On Exercise 2.2

• Exceptions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-41 Parameter Passing

 In C#, parameters and their arguments can be • Value types • Reference types  For value types, a copy of the data itself is made • This is known as pass-by-value  For reference types, only the address of the data is passed • This is known as pass-by-reference  Similarly, when returning data • Value types are returned-by-value • Reference types are returned-by-reference

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-42 Passing Arguments

 Let’s compare the default passing of value and reference types MEMORY

public static void Main() { int[] code = new int[2]; code[0] = 4136; code[1] = 5943; int num = 9988; Change(num, code); Console.WriteLine("num = " + num); Console.WriteLine("code[0] = " + code[0]); Console.WriteLine("code[1] = " + code[1]); }

public static void Change(int n, int[] c) { c[0] = c[1]; c[1] = n++; }

What is displayed for num and code?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-43 Passing Value Types by Reference

 The parameter passing defaults can be changed MEMORY • ref keyword can be used to pass a value type by reference • out allows a variable to be initialized from within a method

public static void Main() { Must be used int[] code = new int[2]; by the caller code[0] = 4136; code[1] = 5943; int num = 9988; Change(ref num, code); Console.WriteLine("num = " + num); Console.WriteLine("code[0] = " + code[0]); Console.WriteLine("code[1] = " + code[1]); } public static void Change(ref int n, int[] c) { c[0] = c[1]; c[1] = n++; } Must be part of the signature What is output for num and code now?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-44 Chapter Contents

• Namespaces and Methods

• Data Types and Literals

• Hands-On Exercise 2.1

• Expressions and Operators

• Arrays and Strings

• Parameter Passing  Loops and Conditionals

• Hands-On Exercise 2.2

• Exceptions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-45 Loops and Conditionals

 C# has a number of traditional loop and conditional statements if if (a > b) c = d;

if/else if (a > b) c = d; else c = e;

switch see subsequent slide

while while (a > b) c = d;

do/while do { a = something(); } while (a > b);

for for (int i = 0; i < a; i++) something(i);

foreach see subsequent slide

goto label: … other code … goto label;

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-46 The foreach Loop

 On occasion, it is desirable to apply the same operation to all elements in a collection • Arrays are an example of a collection  The foreach loop makes this very convenient  Example:

void RunPayroll(string[] people) { foreach(string person in people) { Console.WriteLine("Payroll running for " + person); ComputePayroll(person); } }

C:\Course\419\Samples\foreachLoop

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-47 switch Statement

 An alternative to the case construct (if/else-if/else) is the switch • Only a null case (no statements) can fall through to next case

… statements … int cpu = GetProcessorType();

switch(cpu) Must be a simple data type { case 8086: Console.WriteLine("Sell it on ebay?"); break; This is the only legal fall-through case 386: case 486: Console.WriteLine("Too old for Windows XP"); break; default: RunWindowsXP(); break; } … statements …

C:\Course\419\Samples\switchStatement

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-48 Chapter Contents

• Namespaces and Methods

• Data Types and Literals

• Hands-On Exercise 2.1

• Expressions and Operators

• Arrays and Strings

• Parameter Passing

• Loops and Conditionals  Hands-On Exercise 2.2

• Exceptions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-49 Hands-On Exercise 2.2

In your Exercise Manual, please refer to Hands-On Exercise 2.2: Expressions, Casting, and Arrays

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-50 Chapter Contents

• Namespaces and Methods

• Data Types and Literals

• Hands-On Exercise 2.1

• Expressions and Operators

• Arrays and Strings

• Parameter Passing

• Loops and Conditionals

• Hands-On Exercise 2.2  Exceptions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-51 Part 1: Hidden Bugs Do Now

Did you know there is a serious error in our monetary conversion program? 1. Launch VS and open the solution for the currency converter found in C:\Course\419\Do Now Demo\Do22

2. Execute the program 3. When prompted, enter one hundred instead of 100

4. What happens? • Click Close Program if you get a dialog box 5. Leave this solution open for now

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-52 Exceptions

 Exceptions are a reliable, standardized mechanism for handling errors • And are used extensively in the .NET Framework library  A class-type object inherited from System.Exception  Numerous exceptions are defined in .NET Framework • System.OverflowException • System.ArithmeticException • System.IO.IOException • System.IO.FileNotFoundException • Many, many more  Can define our own exceptions Failure to properly handle exceptions results in very unreliable programs  Inheritance will be discussed in the next chapter

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-53 Part 2: Exceptions Do Now

The program would have been better to process exceptions: public static decimal GetAmount(string prompt) { decimal data = 0.00M; bool no_data = true; while (no_data) { try { System.Console.Write(prompt); string input = System.Console.ReadLine(); data = decimal.Parse(input); if (data > 0.00M) no_data = false; } catch(FormatException exc) { Console.WriteLine(exc.Message); } } return data; }

 Edit the program you just tested to include the try/catch statements above, then compile and test; what happens now?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-54 try…catch…finally

 The general form of exception processing is

try { // Code that might throw exception-type-1 or exception-type-2 } catch (exception-type-1 variable-name) { // Go here if above code throws exception-type-1 } catch (exception-type-2 variable-name) // Multiple catch optional { // Go here if body of try throws exception-type-2 } finally // Optional { // Go here in every case, even if no exception thrown // Usually put all cleanup actions here }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-55 Exception Flow

 When an exception is thrown, the following events occur 1. A new exception object is created 2. Flow of the program skips all statements (except finally clauses) from where the exception was thrown to the nearest matching catch 3. If there is no matching catch, the program exits ◦ An unhandled exception message is given ◦ A stack trace is given

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-56 using Blocks

Later in the course, we will discuss disposable objects • Such as the I/O classes like StreamWriter  For disposable objects, we can implement a using block • A pleasant alternative to the try-catch-finally syntax • Equivalent of a try-finally (no catch)

using(SomeDisposableObject dobj = new SomeDisposableObject()) { // Logic that might throw exception } The object will be automatically disposed (closed) in the implied finally at the end of the using block  Would still need to catch the actual exception somewhere later if necessary

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-57 Throwing an Exception

 Throwing exceptions is the preferred mechanism for handling errors in C#  throw keyword is used for this purpose

 Example: An error that we cannot handle occurs here public void Deposit(decimal amount) { if (amount <= 0.00M) { throw new ArgumentException("Amount must be positive"); } … statements … } These statements are bypassed if the exception is thrown

 Execution will continue at nearest Exception catch block • Or the program will exit if there isn’t one

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-58 Avoiding Unwanted Exceptions

 Some exceptions (arithmetic overflow and conversion errors) can be controlled in specific sections of code using checked/unchecked blocks • These can be nested  For example: public static void Main() { An arithmetic overflow int val = int.MaxValue; exception will not be thrown here, regardless unchecked of the compiler settings { val++; } … other processing … }

 A compiler option switch controls the default throwing of arithmetic overflow exceptions • The Visual Studio default is not to throw arithmetic overflow exceptions • Might not be the default in other compilers

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-59 Chapter Contents

• Namespaces and Methods

• Data Types and Literals

• Hands-On Exercise 2.1

• Expressions and Operators

• Arrays and Strings

• Parameter Passing

• Loops and Conditionals

• Hands-On Exercise 2.2

• Exceptions  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-60 Review Questions

What is a namespace?

What is the relationship between overloading and a method’s signature?

Like variables, expressions have both ______and ______What is the syntax of the foreach loop?

Under what circumstances are implicit type conversions allowed?

What is meant by a type cast?

What are six key words associated with exceptions?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-61 Chapter Summary

In this chapter, we have examined  The fundamental differences between C# and other programming languages  Program organization  Data types  Operators and expressions  Strings and arrays  Loops and conditionals  Exceptions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-62 Chapter 3

User Interface Development Chapter Objectives

In this chapter, we will  Discuss the architecture of an object-oriented application  Outline the basics of desktop and ASP.NET Web Forms • For desktop and web user interfaces  Start the course’s theme project

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-2 Chapter Contents

 Controls and Properties

• Forms Layout

• Page Layout

• Events

• The Code Behind

• Message Boxes

• Hands-On Exercise 3.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-3 The Three-Layer Model

 Experience has shown over the years that it is best to develop an application in three layers • View or presentation layer View Rules Data • Business rules layer • Data access layer Data

 Each layer should be independent from the others so that they can be substituted and/or logic reused as needed • Called loose coupling  Improves extensibility and maintainability by providing a “separation of concerns” • Facilitates changing the view or adding services or tests

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-4 GUI Philosophy

All GUIs—web or desktop—are ...  Event-driven • Responds to user requests at the time the user makes them ◦ In the order in which they are made • Requests are made using a pointing device  Inherently object-oriented Visual Studio comes with RAD tools that allow us to do the layout visually • Simply select a control like a button and drag it to a form • Then modify its properties using the properties window  In namespaces • System.Windows.Forms for desktop Windows Forms • System.Web.UI for ASP.NET Web Forms

GUI = graphical user interface RAD = rapid application development

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-5 Controls

 The controls for Windows Forms and ASP.NET are very similar • Some are virtually identical (ListBox) • Some are only for Windows Forms (Timer) • Some are unique to ASP.NET (LinkButton) for navigation However …  ASP.NET controls appear in an HTML document with tags like • Pure HTML is generated “automagically” when rendered to the browser, often containing multiple HTML controls plus JavaScript

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-6 Drawing Properties

 All controls have properties associated with them  In System.Drawing namespace  These include such items as • Fonts • Foreground color • Background color • Visibility  The (Name) property determines what the control is called  Most can be set during layout in Visual Studio using the property sheet  Can also be set programmatically using direct property assignment button1.BackColor = Color.LightCoral;

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-7 Chapter Contents

• Controls and Properties  Forms Layout

• Page Layout

• Events

• The Code Behind

• Message Boxes

• Hands-On Exercise 3.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-8 Container Controls

 In Windows Forms, a form is a container on which to place other controls • This is what we most often think of as a “window” ◦ Has a frame, title bar, minimize, and maximize controls, etc.  There are other container controls, such as a panel • We can put a control in a panel and the panel in the form; or • A control in a panel, the panel in another panel, that panel in a form, etc.

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-9 Anchoring and Docking

 When controls are added to a container, their size and location can be set absolutely in terms of x,y coordinates • This is inconvenient, especially if a form is resized by the user Docking quadrants  Anchoring controls the position top from which a control is “attached” • For example: top, left • Generally, spacing is retained • Control might be stretched left fill right  Docking divides the container into five quadrants, as shown • Control is resized as appropriate to fit the area bottom • Usually, a panel is put into each quadrant, then other controls put on the panel

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-10 Desktop GUI Operation

 Execution of a Windows Forms application is controlled by the Application class  Application.Run(… application …): starts the message pump so that events are dispatched to the specified application  Application.Exit(): stops the message pump, closes the window, and exits

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-11 Instructor Demonstration Demo

 Your instructor will now demonstrate the GUI development capabilities of VS • Please be sure to notice ◦ The various types of controls available ◦ How they are placed onto the form ◦ How they are anchored and docked ◦ How to modify their properties ◦ How to run the program ◦ How to generate an event method

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-12 Chapter Contents

• Controls and Properties

• Forms Layout  Page Layout

• Events

• The Code Behind

• Message Boxes

• Hands-On Exercise 3.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-13 ASP.NET Operation

 A thin-client web page operates differently than a desktop GUI  Regardless of how it looks when the layout is done, “pure” HTML and JavaScript are delivered to the browser  However, pages can be posted back, allowing for interactive event-driven operation between the user and the application Request a dynamic web page Request a static web page http://someweb/somepage http://someweb/somepage.html .aspx

Web Web server server

HTML HTML

Page is located and its HTML contents Program is executed and the program are sent to the browser by the server itself sends HTML to browser

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-14 Layout in ASP.NET

 In ASP.NET, a “form” is a web page  Drag and drop is similar, but layout is usually done using HTML tables • No anchoring or docking per se  Designer essentially eliminates the need to see HTML • Transparently separates the C# from the HTML • Developer can concentrate on C# logic  Can view the page in • Design view • HTML view • C# code-behind view (most common)  The extension for an ASP.NET web page is • pagename.aspx for the page itself • pagename.aspx.cs for the C# code behind

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-15 Navigation

 It is the nature of web applications to move the user from page to page • Called navigation  Can be done directly using a hyperlink • URL property specifies where user should be directed  Navigation can also be done from the code behind  Most common is Response.Redirect(…URL…) • Informs the browser to go to the specified URL • URL is shown in the browser

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-16 ASP.NET Prerequisites

To run an ASP.NET web application, software installation must include  On the server • Microsoft IIS (WWWPS) on a Windows platform ◦ Or appropriate alternative if running on Linux or UNIX • The .NET Common Language Infrastructure ◦ Includes the ASP.NET programming library  On the client • A reasonably modern web browser

IIS = Internet Information Services WWWPS = World Wide Web Publishing Service

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-17 Instructor Demonstration Demo

 Your instructor will now demonstrate the web application development capabilities of VS • Please be sure to notice ◦ The similarities between Windows.Forms and WebForms ◦ The design view ◦ The HTML view ◦ The standard HTML delivered to the browser

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-18 Chapter Contents

• Controls and Properties

• Forms Layout

• Page Layout  Events

• The Code Behind

• Message Boxes

• Hands-On Exercise 3.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-19 Handling Events

 Laying out a form or page lets you see what the application will look like But …  It needs to be connected to application logic in C# code behind the form  Without this, GUI programs will not do any real processing • Buttons might appear to indent when clicked ◦ But no business logic will be executed in response to the click  We need to add event handling

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-20 About Events

 User interaction with a control generates an event • There are many different types of events; e.g.: ◦ Pressing and releasing a button ◦ Selecting an item from a list ◦ Loading a form or page  Events contain information about the control that generated the event  In ASP.NET, events fire on the server’s side when the page is posted back • When a submit button is pressed • When triggered by JavaScript ◦ Controls can be set to automatically post back, which will nicely include the appropriate JavaScript  Events must be processed by an event handler • The handler delegates the processing of an event by calling a method (function) that we write

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-21 Event Processing

 Event handling in Windows Forms and ASP.NET

Processing Sent to the handler delegated to registered for the a method in event our GUI program

Fielded by CLI

Processing User generates method event (e.g., specified when button push) event handler created

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-22 Chapter Contents

• Controls and Properties

• Forms Layout

• Page Layout

• Events  The Code Behind

• Message Boxes

• Hands-On Exercise 3.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-23 The Code Behind

 For both Windows Forms and ASP.NET, Visual Studio generates most of the code for you • Except what you put in your event methods  Your event methods and the control definitions are placed in different partial class segments • In different files We will review enough to get a general overview of what is happening • Other information on partial classes, event handlers, and delegates will be covered later in the course

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-24 The Code Behind

 Visual Studio will generate code that looks something like the following:

namespace SomeNamespace { public partial class SomeForm: System.Windows.Forms.Form { ... Uses inheritance of } a Windows Form } namespace SomeNamespace { public partial class SomePage: System.Web.UI.Page { ... } Uses inheritance of a Web page }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-25 How Visual Studio Adds a Control

 When we drag and drop a control in the designer and make changes in its property sheet  Visual Studio writes the code to 1. Create an instance of the control 2. Set its properties

partial class SomeForm { … other code … void InitializeComponent() { … initialization of other controls and properties … button1 = new Button(); button1.Text = "HELP"; Create the button button1.BackColor = Color.LightCoral; ... } } Set the button properties

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-26 How Visual Studio Adds Event Handling

 When we double-click a control in the designer …  Visual Studio adds event handling in the code behind by: 1. Creating an event handler (System.EventHandler) 2. Passing the “address” of our event method to the event handler ◦ Called a delegate 3. Registering the event handler by connecting it to the control’s property that will generate the event

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-27 How Visual Studio Adds Event Handling

 This example shows how an event handler is added • Note the special += operator to register an event handler

… same as on previous listing …

public InitializeComponents() Create event { handler … create controls and other code … button1.Click += new EventHandler(button1_Click); … } Delegate to our Register the handler event method

protected void button1_Click(object sender, EventArgs e) { label1.Text = "No help for you"; // Tell truth button1.Text = "SIGH"; // Reconfigure }

What should the output look like after the button is clicked?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-28 Chapter Contents

• Controls and Properties

• Forms Layout

• Page Layout

• Events

• The Code Behind  Message Boxes

• Hands-On Exercise 3.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-29 Message Boxes

 A special case of GUI programming is a message box • Sometimes called a dialog box  Typically appears on top of a Windows form  Has a special static method called Show to make these dialogs easy • Static methods can be executed without creating an object instance • Returns a DialogResult enum  Various overloads are available, but the most common is:

MessageBoxButtons Title bar text Parent form selection MessageBox.Show(this,"Message","Title",buttons,icons)

Message text MessageBoxIcon selection

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-30 MessageBox Example

 Report a warning …

void GiveWarning() { … Statements … DialogResult dr = MessageBox.Show(this, "The sky is falling!", "Chicken Little", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (dr == DialogResult.Cancel) return; // Don’t do anything … Do something about it … }

Resultant pop-up  dialog box

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-31 Chapter Contents

• Controls and Properties

• Forms Layout

• Page Layout

• Events

• The Code Behind

• Message Boxes  Hands-On Exercise 3.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-32 The Theme Project

 We are about to begin the theme project for the course—a card game called “The Eyes Have It,” or “Tehi” • Used in some schools to help children practice addition and multiplication  Chosen because most participants will already be familiar with common playing cards • The game is easy to learn

Please inform your instructor if you are not familiar with common playing cards

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-33 Two Environments

 Most exercises provide the choice of a desktop version using Windows Forms or a web version using ASP.NET  You can switch back and forth at the start of each exercise if you like But …  There won’t be time for you to use both environments for every exercise during class • Gives you something to do after the course is over

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-34 Hands-On Exercise 3.1

In your Exercise Manual, please refer to Hands-On Exercise 3.1a: Writing Windows Forms Programs or Hands-On Exercise 3.1b: Developing a Web Application

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-35 Chapter Contents

• Controls and Properties

• Forms Layout

• Page Layout

• Events

• The Code Behind

• Message Boxes

• Hands-On Exercise 3.1  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-36 Review Questions

What is an event in Windows Forms or ASP.NET?

What is an event handler, and what arguments are passed to it?

What is a DialogResult?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-37 Chapter Summary

In this chapter, we have  Discussed the architecture of an object-oriented application  Outlined the basics of desktop Windows Forms and ASP.NET Web Forms • For desktop and web user interfaces  Started the course’s theme project  For more information on ASP.NET, see • Course 2621, Building ASP.NET Web Forms Applications

2621

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-38 Chapter 4

Defining User-Written Data Types Chapter Objectives

In this chapter, we will introduce  The C# facilities for defining your own data types  Object-oriented abstraction

 Classes and structures  Fields, methods, and properties  Inheritance

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-2 Chapter Contents

 Object-Oriented Philosophy

• C# Class Definitions

• Constructors

• The this Reference

• Hands-On Exercise 4.1

• Properties

• Hands-On Exercise 4.2

• Inheritance

• Hands-On Exercise 4.3

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-3 What Is Object-Oriented?

 Object-oriented (OO) programming is a style of programming • Don’t need an OO programming language ◦ But having one makes life easier  OO programming is all about abstraction • Meaning writing new data types • Usually matching objects from the real world  Objects in the real world have SBI • State • Behavior • Identity

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-4 Three Pieces of PIE

 C# facilitates OO programming by providing support for the three object-oriented pieces of PIE • Polymorphism: Ability to access an inherited class through the interface of the class it was inherited from • Inheritance: Ability to define a class by extending a previously defined class • Encapsulation: Ability to define a class so that its state and implementation is hidden behind its behavior  What are the advantages of using an OO programming style?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-5 Defining Our Own Data Types

 C# has two similar constructs for defining data types (like a cookie cutter) • A class if the type is to be used by reference • A struct if the type is to be used by value  An object is an entity in memory (the cookies) • Structure objects are usually created directly on the stack • Class objects are typically created on the heap using the new keyword

 Remember, you can eat only the cookie!

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-6 Creating Structures

 Structures are used much less frequently than classes, but are useful for • Creating in-memory records that can be passed as a single item • Small mathematical types with symbolic operators namespace ComplexMath  struct fields default to private { public class Program namespace ComplexMath { { public static void Main() public struct complex Create directly { { on the stack complex c1; public double real; c1.real = 3.426; public double imaginary; c1.imaginary = 2.45; ... DoSomeCalculation(c1); } } } } } Pass by value as  Our discussion will focus on classes a single item • Most features will work equally well with structures

C:\Course\419\Samples\ComplexTest

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-7 UML

 For simplicity, in discussing our object-oriented programs, the pictorial capabilities of the Unified Modeling Language (UML) will be used • The theory is that one picture is worth 10,000 words  UML is an industry-standard notation for describing OO programs  Tendered by the Object Management Group (OMG) as a standard  Developed by Rational Software Corporation (now part of IBM) • Combined work of Booch, Rumbaugh, and Jacobson See the Object Management Group and IBM/Rational Technologies at www.omg.org and www.rational.com, respectively

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-8 UML Class Notation

 An example of the UML notation for a class or structure is: BankAccount  Name of the class balance : decimal  Fields—encapsulated (private) data that acctnum : ulong defines the state Deposit(amount : decimal) Withdraw(amount : decimal)  Methods—exposed (public) functions that Close() define the behavior

 The interface of a class is the list of all its methods; in this case, the interface includes Deposit(), Withdraw() and Close()  The business rules are in the methods • Encapsulation forces the user to follow the business rules in the interface  Additional UML notation will be introduced as needed during the course

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-9 Chapter Contents

• Object-Oriented Philosophy  C# Class Definitions

• Constructors

• The this Reference

• Hands-On Exercise 4.1

• Properties

• Hands-On Exercise 4.2

• Inheritance

• Hands-On Exercise 4.3

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-10 C# Class Definitions

 The general form of a C# class definition is [Modifiers] class ClassName [: [Base Class[,]] [Interfaces[,]]] { … private fields … … public methods and properties … }  ClassName is the programmer-defined class name  Optional [Modifiers] provide information as to the nature of the class • public indicates availability to other objects in any assembly • internal indicates availability to any other object in the same assembly • Left blank (the default) is the same as internal  public methods and properties are accessible from any client code  private fields encapsulate the state, and are accessible only from the methods and properties within the same class  Base Class inherited from or Interfaces implemented in the class

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-11 A BankAccount Class

 Here is the C# code for the BankAccount class we saw previously in UML • It has only fields and methods using System; namespace Banking { public class BankAccount { private fields private decimal balance; private ulong acctnum;

public void Deposit(decimal amount) { balance = balance + amount; } public public void Withdraw(decimal amount) methods { can access the if (balance >= amount) private fields { balance = balance – amount; } else throw new ArgumentException("NSF"); } … other methods … } }

C:\Course\419\Samples\BankAccount1

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-12 Using the BankAccount Class

 Once we have defined the class, we can make object instances using System; namespace Banking Create BankAccount { instances (objects) public class Bank { public static void Main() { BankAccount a1 = new BankAccount(); BankAccount a2 = new BankAccount(); a1.Deposit(100.00m); a2.Deposit(500.00m); Access the data by a2.Withdraw(50.00m); calling methods a1.Deposit(50.00m); //Console.WriteLine("Balance = " + a2.balance); } } Error—encapsulation violation }

C:\Course\419\Samples\BankAccount1

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-13 Instance Data

 When created, each object has its own instance data • BankAccount a1 = new BankAccount(…); a1 a2

Deposit Deposit Methods Withdraw Withdraw Close Close

Instance balance acctnum balance acctnum data

Do not confuse instance data with static data • Static is shared among all instances

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-14 object Class

 In C#, if a class is not explicitly inherited from another class, it implicitly inherits from object  Has many useful methods we get “for free”

object

GetType() : Type Tells what type of ToString() : string object we are …many more… Converts an object to its string representation— often overridden

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-15 Overriding ToString()

 It is common to implement ToString() in a class • Provides convenient readable output

using System; namespace Banking { public class BankAccount { Must tell compiler private decimal balance; we are replacing private ulong acctnum; the one in object … as before … public override string ToString() { return "Account:" + acctnum + " " + "Balance:" + balance; } } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-16 Chapter Contents

• Object-Oriented Philosophy

• C# Class Definitions  Constructors

• The this Reference

• Hands-On Exercise 4.1

• Properties

• Hands-On Exercise 4.2

• Inheritance

• Hands-On Exercise 4.3

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-17 The Need for Constructors

 How do our fields get initialized?  In our previous example, we appear to be using uninitialized data • balance and acctnum were initialized to 0 automatically for us  Rather than the default value of 0 being used for fields, you might want to initialize them to some alternative values • This is common in the real world, so we want to do the same in our classes ◦ For example, you cannot be an employee in Canada unless you have a Social Insurance Number (SIN)  In C#, a special method called a constructor is invoked when an object is created • These can be used to initialize fields accordingly • They can be overloaded

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-18 Default Constructor

 The name of a constructor is the same as the name of its class • The default constructor for a class takes no arguments • It is invoked when an object is defined with no explicit initial value provided  Unlike other methods we’ve seen, a constructor is declared with no return type, and it may not return a value, not even void • The constructor’s job is to initialize the internal state of a new object  The system will provide a default constructor if we do not write any other constructor(s) • The system-provided default constructor will call only the default constructors for each item of member data  Primary types will be initialized to 0, false, or null as appropriate • false for boolean types • null for reference types • 0 for all others

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-19 Overloaded Constructors

 A bank account with constructors might look like this:

public class BankAccount { private decimal balance; private readonly ulong acctnum; public BankAccount(ulong initnum) { acctnum = initnum; balance = 0.0m; } public BankAccount(ulong initnum, decimal initbal) { acctnum = initnum; balance = initbal; } … deposit, withdraw and other methods … }

 readonly means the value can only be assigned in a constructor

C:\Course\419\Samples\BankAccount1

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-20 Overloaded Constructors

 Note that since we did not write a default constructor, a bank account can no longer be constructed using BankAccount a = new BankAccount() • The client code is forced to provide certain data during initialization using System; namespace Banking { public class Bank { public static void Main() { //BankAccount a1 = new BankAccount(); // Won’t compile! BankAccount a2 = new BankAccount(112677L, 200.00M); // OK ... } } }

 We can write a default constructor, too, if it is needed

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-21 Chapter Contents

• Object-Oriented Philosophy

• C# Class Definitions

• Constructors  The this Reference

• Hands-On Exercise 4.1

• Properties

• Hands-On Exercise 4.2

• Inheritance

• Hands-On Exercise 4.3

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-22 Data Placement

 In C#, data can only be defined as • Fields (instance or static) • Local variables • Parameters public class Person { private string name; Fields private int age; public void SomeMethod(string s) { int i; double x; Parameters … statements … } Local variables public void SetName(string name) { this.name = name; } } If there is ever confusion, use this to specify

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-23 The this Reference

 When an instance method or property is invoked, a special reference called this is set to point to that object • this is a keyword meaning the current object • It is meaningful only in the body of an instance method or property

current object

this … instance data …

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-24 Chapter Contents

• Object-Oriented Philosophy

• C# Class Definitions

• Constructors

• The this Reference  Hands-On Exercise 4.1

• Properties

• Hands-On Exercise 4.2

• Inheritance

• Hands-On Exercise 4.3

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-25 The Theme Project

 In the previous chapter, we produced the view for “The Eyes Have It”

View Rules Data

Data

 In the next series of exercises, we will evolve new reusable data types to serve as the business rules layer • We will start with the PlayingCard class

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-26 Hands-On Exercise 4.1

In your Exercise Manual, please refer to Hands-On Exercise 4.1: Defining Classes

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-27 Hands-On Exercise 4.1 Debrief

 Although we can display a string representation of a playing card, we cannot find out its rank, suit, or if it is face up or down  How can we provide access to encapsulated data?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-28 Chapter Contents

• Object-Oriented Philosophy

• C# Class Definitions

• Constructors

• The this Reference

• Hands-On Exercise 4.1  Properties

• Hands-On Exercise 4.2

• Inheritance

• Hands-On Exercise 4.3

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-29 public Fields?

 For quality of encapsulation, public fields are undesirable  Traditional OO languages often have many getter and setter methods using System; namespace Banking { public class BankAccount { private decimal balance; … other fields … … other methods … public decimal GetBalance() { return balance; } } } Console.WriteLine("Balance: " + a2.GetBalance());

 Can be tedious for user: thing.SetValue(thing.GetValue() + 100.00); Must call the accessor method  This would be more convenient: thing.Value += 100.00;

 Properties enable this ease of use without sacrificing encapsulation

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-30 Implementing Properties

 The general syntax for properties in C# is visibility type name { visibility get { … logic … return field; } visibility set { … logic … field = value; } } • visibility is the encapsulation accessibility of the property ◦ public, protected • type is the data type of the property ◦ Does not need to match the type of a field • field is the field apparently being manipulated • value is a key word representing an instance of the type provided

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-31 Implementing Properties

 For example, properties in the bank account using System; namespace Banking { public class BankAccount Field starts with lowercase { private decimal balance; private string owner; … other fields and methods … public decimal Balance { get { return balance; } } public string Owner { Property starts set with uppercase { if (value.Length != 0) owner = value; else throw new Exception("Owner name cannot be blank"); } get { return owner; } } } } a2.Owner = "Jasper Kent"; Console.WriteLine("Balance: " + a2.Balance);

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-32 About Properties

 Properties do not need to have a corresponding or matching field  In a property, if set is not provided, the property becomes read-only • Also true for get—write-only is occasionally useful  Like methods, properties can be static • Apply at the class level, not the instance level  The Microsoft convention for naming a property is initial capitalization • SomeName, not some_name When visual controls are written in C#, properties appear in VS as a property sheet

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-33 Property Clutter

 Although properties are convenient for the client, classes can often get quickly cluttered with repetitive property code • In many cases, they have very simple encapsulation (just set and get) public class BankAccount  For example: { private decimal balance; public decimal Balance { get { return balance; } } private ulong acctnum; public ulong Number { get { return acctnum; } } private decimal interestRate; public decimal Rate { get { return interestRate; } set { interestRate = value; } } public void Deposit(decimal amount) Note: Methods { reference fields balance = balance + amount; } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-34 Auto-Implemented Properties

 As a convenient shortcut, auto-implemented properties can be used  These retain all the benefits of encapsulation and properties without the clutter It saves lots of typing, too!

public class BankAccount { public decimal Balance { get; private set; } public ulong Number { get; private set; } public decimal Rate { get; set; } public void Deposit(decimal amount) { Balance = Balance + amount; } } Methods reference the property  Auto-implemented properties are just a convenient alternative syntax  Auto-implemented properties can be initialized in their definitions as in • public decimal Rate { get; set; } = .02M;

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-35 Properties vs. Methods

 When should a property be used and when should a method be used? • Properties appear to the client as data access • Methods appear to the client as processes  For example, in our bank account class • Deposit and Withdraw would be best as methods • Balance would be best as a get-only property  There is no formal syntax for property specification in UML, so we will use {get,set} and place it in the method area

BankAccount

Deposit(amount : decimal) Withdraw(amount : decimal) Balance{get} : decimal Number{get} : ulong

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-36 Chapter Contents

• Object-Oriented Philosophy

• C# Class Definitions

• Constructors

• The this Reference

• Hands-On Exercise 4.1

• Properties  Hands-On Exercise 4.2

• Inheritance

• Hands-On Exercise 4.3

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-37 Hands-On Exercise 4.2

In your Exercise Manual, please refer to Hands-On Exercise 4.2: Implementing Properties

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-38 Hands-On Exercise 4.2 Debrief

 Properties make it convenient to obtain or set encapsulated data  You could make the case that none of the card data should be accessible if the card is face down • We could throw a “CheatException”  That level of abstraction is probably not practical, however

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-39 Chapter Contents

• Object-Oriented Philosophy

• C# Class Definitions

• Constructors

• The this Reference

• Hands-On Exercise 4.1

• Properties

• Hands-On Exercise 4.2  Inheritance

• Hands-On Exercise 4.3

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-40 Inheritance

 Inheritance is a fundamental way that humans organize the real world • Inheritance is also called specialization—technically more accurate  For example: “A manager is an employee who supervises other employees” “A car is a kind of vehicle designed to carry passengers” “A savings account is a bank account that yields interest”  Notice the “is a” or “is a kind of” form  This promotes reuse because we can extend an existing class that does almost what we want

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-41 Freight Car Analysis

Consider the freight car examples below; how would you describe each of them in terms of freight cars?

What are the general features and what are the unique ones?

Gondola Boxcar Tanker

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-42 Freight Car Analysis

 We could create an inheritance hierarchy that is represented in UML as:

FreightCar length : int  Base class (the class inherited from) width : int All of the common or general fields height : int … other fields … and methods are here … other methods … Length { get } : int Inheritance symbol

Tanker Boxcar Gondola radius : double boxcar unique fields gondola unique  Derived classes (the fields classes inheriting) Radius { get } : double Boxcar unique methods gondola unique All the unique fields methods and methods are here

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-43 Inheritance Example

 In C#, we can inherit Tanker from FreightCar using: using System; namespace Trains { public class FreightCar { private readonly int length, width, height; private readonly string roadNumber; public string RoadNumber {get { return roadNumber; } } public FreightCar(string rn, int ln, int wd, int ht) { roadNumber = rn; length = ln; width = wd; height = ht; } } using System; } namespace Trains Inheritance { syntax public class Tanker : FreightCar { private readonly double radius; public double Radius { get { return radius; }} … other tanker unique fields and methods … } }

C:\Course\419\Samples\TankerInheritsFreightCar

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-44 Inheritance Example

 Now Tanker instances can be created and used

using System; namespace Trains Create Tanker { instance public class Trains { public static void Main() { Tanker car = new Tanker(…initialization info…); double rad = car.Radius; string num = car.RoadNumber; Use behavior unique } to the Tanker class } } Use behavior inherited from FreightCar

C:\Course\419\Samples\TankerInheritsFreightCar

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-45 Initializing the Base Class

 In the previous example, we omitted the details of construction  Had we written the following, it would not have compiled; why?

using System; namespace Trains { public class Tanker : FreightCar { private readonly double radius; public double Radius {get{ return radius; }} public Tanker(string rn, int ln, int wd, int ht, double rd) { roadNumber = rn; length = ln; width = wd; height = ht; radius = rd; } } }

C:\Course\419\Samples\TankerInheritsFreightCar

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-46 “Inside Out” Construction

 There are no methods or properties we can use to initialize the base-class fields, so we must call the base-class constructor But …  Derived-class objects must be constructed “inside out” • The base class must be constructed first • Then the derived-class fields can be initialized in the constructor  If the derived-class constructor does not invoke an explicit base-class constructor, the default base-class constructor is used • If there is no default base-class constructor, it is an error

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-47 Derived-Class Constructor Syntax

 The proper syntax for our Tanker constructor would be:

using System; namespace Trains { public class Tanker : FreightCar { private readonly double radius; Note : public double Radius {get{ return radius; }} public Tanker(string rn, int ln, int wd, int ht, double rd) : base(rn, ln, wd, ht) { radius = rd; } } Call base constructor } before we execute body of Tanker constructor

C:\Course\419\Samples\TankerInheritsFreightCar

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-48 Inheritance Points to Ponder

 It is OK for a base-class reference to point to a derived-class object FreightCar car = new Tanker();

 A derived-class method can call a base-class method with the same signature using the keyword base public override void Foo() { … other logic … base.Foo(); … other logic … }

We will discuss these topics in more detail later in the course

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-49 Chapter Contents

• Object-Oriented Philosophy

• C# Class Definitions

• Constructors

• The this Reference

• Hands-On Exercise 4.1

• Properties

• Hands-On Exercise 4.2

• Inheritance  Hands-On Exercise 4.3

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-50 Hands-On Exercise 4.3

In your Exercise Manual, please refer to Hands-On Exercise 4.3: Leveraging Inheritance

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-51 Chapter Contents

• Object-Oriented Philosophy

• C# Class Definitions

• Constructors

• The this Reference

• Hands-On Exercise 4.1

• Properties

• Hands-On Exercise 4.2

• Inheritance

• Hands-On Exercise 4.3  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-52 Review Questions

What is meant by encapsulation? Why is it useful?

In C#, what does a reference hold?

How do we avoid having an improperly initialized object?

When should you use a method? When should you use a property?

What return type should be specified for a constructor?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-53 Review Questions

What is the “is a” relationship?

What is the difference between a field and a property?

What is the syntax to implement an auto-implemented property?

What is the syntax to call a base-class constructor from a derived-class constructor?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-54 Chapter Summary

In this chapter, we have introduced  The C# facilities for defining your own data types  Object-oriented abstraction

 Classes and structures  Fields, methods, and properties  Inheritance

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-55

Chapter 5

The .NET Framework Chapter Objectives

In this chapter, we will discuss  The .NET Framework  Utility classes  Basic I/O classes  Serialization  ASP.NET Framework  Collection classes

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-2 Chapter Contents

 .NET Framework

• I/O Classes

• Collection Classes

• ASP.NET Framework

• Hands-On Exercise 5.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-3 .NET Framework

 Being a good C# programmer requires more than just knowledge of the language; it also requires knowledge of the .NET Framework  The .NET Framework includes an enormous class library • Available to all CLR languages  For simplicity, it is • Organized into namespaces • Documented as hyperlinked web pages  This course uses the .NET Framework library version 4

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-4 Major .NET Namespaces

Namespace Description System.Collections Collections System.Collections.Generic Generic collections System.ComponentModel Used as basis for .NET component infrastructure System.Timers Provides timer and session capabilities

System.Data.SqlClient ADO.NET SQL Server database support

System.Data.Linq LINQ database support System.Drawing System.Windows.Forms Comprehensive desktop GUI support System.IO Stream-based input/output and flat file support System.Net Networking, TCP/IP, and socket support System.Threading Lightweight threading support System.Web System.XML Support for ASP.NET and XML web applications  Many, many more

ADO = ActiveX Data Object TCP/IP = Transmission Control Protocol/Internet Protocol

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-5 A Few Useful Classes

 Throughout the course, we will be using items from most of the major .NET framework namespaces  Here are a few utility classes and structs you might find useful initially:

Class or struct Description System.Random Next method returns next pseudo-random number System.DateTime (struct) Now property returns current date and time System.TimeSpan (struct) Time span compatible with DateTime

System.Environment Provides environment-specific information such as CurrentDirectory and NewLine System.IO.File File.Exists(…) and File.Delete(…), etc. System.IO.Directory Similar to System.IO.File but for directories System.Array Generalized array class

 See the help documentation and/or IntelliSense for more information

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-6 Chapter Contents

• .NET Framework  I/O Classes

• Collection Classes

• ASP.NET Framework

• Hands-On Exercise 5.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-7 I/O Streams

 The Console class we have been using is actually just StreamWriter and StreamReader classes • Part of a set of generalized I/O stream classes • Found in namespace System.IO  I/O streams can be used for reading and writing flat data files, over the network or for web pages  This example writes to the file message.txt

using System.IO; public class Something Append control—false { means create new file public static void Main() { StreamWriter fout = new StreamWriter("message.txt", false); fout.WriteLine("Your balance is ${0:F2}",51391.22); fout.Close(); } }

\Course\419\Samples\StreamWriterExample

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-8 Disposing of I/O Streams

 StreamWriter objects are disposable • Implement a Dispose() method where all cleanup will be done • Can be called explicitly or implicitly via a using block

using System.IO; public class Something { public static void Main() { using (StreamWriter fout = new StreamWriter("message.txt", false)) { fout.WriteLine("Your balance is ${0:F2}",51391.22); } } } No need to call Close() Dispose() called automatically

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-9 The Need for Serialization

 Flat text files are convenient only for simple data • Storing whole objects requires that each field be written individually  Often, objects reference other objects • Called an association or an aggregation • Nicknamed the “has a” relationship  Referenced objects must be saved, too • And anything they refer to must also be saved, and so on, and so on  Flat text files are just not suited to this task  Consider the following …

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-10 The Need for Serialization

Memory (now)  Train 101 is pulling two cars; to save its state, we must also save Train 101 Boxcar 29 and Tanker 11 Will Boxcar 29 and Tanker 11 return to the same reference Boxcar 29 Tanker 11 (memory address) tomorrow?

Memory (tomorrow)

Train 101

Boxcar 29 Tanker 11

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-11 Serialization

 Serialization schemes handle the mapping of reference addresses • And allow whole objects to be written at once  Required for compound value–type structures, too • Such as DateTime and Color objects  There are different mechanisms within the .NET Framework for this • Binary Runtime Serialization (BRS) ◦ Supports any type of objects, no matter how complicated • XML serialization ◦ Supports only public read/write properties ◦ Is portable to other languages, notably Java • SOAP serialization ◦ Uses reflective encoding to include all fields and types ◦ Much slower/larger than BRS by about 47 to 1

SOAP = Simple Object Access Protocol or Service Oriented Architecture Protocol

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-12 Serializable Attribute

 To be serialized by BRS, a class must have the [Serializable] attribute • And so must any classes it associates with

[Serializable] public class FreightCar { ... }

 Most library classes are declared [Serializable]  The attribute syntax is part of the C# language • Generally, attributes add “hidden” code to your application and/or act as compilation directives  There are many different attributes in the .NET Framework library • A number will be used later in the course

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-13 Instructor Demonstration Demo

 In the desktop GUI version of Tehi, the player is allowed to change the background color of their game table • Unfortunately, the color is lost when the program is exited and restarted • The BackColor property of the form needs to be saved ◦ This requires serialization because Color is a complex object . Even though it is a value type  Your instructor will now run C:\Course\419\Exercises Completed\Ex51-desktop and highlight the added serialization support for saving color preferences

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-14 Chapter Contents

• .NET Framework

• I/O Classes  Collection Classes

• ASP.NET Framework

• Hands-On Exercise 5.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-15 UML for Freight Train

 In UML, a “freight train” aggregation might be represented as shown • The association verb describes the reason for the association • The multiplicity describes the number of associated objects ◦ * indicates a collection (many) ◦ 0..1 indicates optional (zero to one)

FreightTrain Locomotive Is pulled by 1..2 Locomotive FreightCar Delivers 0..*

Caboose Has on the end 0..1

Caboose

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-16 Freight Train Using Arrays

 The freight train associations could be implemented using arrays

public class FreightTrain Must guess the { maximum size private FreightCar[] cars = new FreightCar[25]; private Locomotive loco1, loco2; private Caboose van; private int carCount; Must ensure there … other methods and constructors … is enough room public void AddCar(FreightCar c) { … confirm enough room, expand and copy if not … cars[carCount++] = c; }

public void ProcessAllCars() { for (int i = 0; i < carCount; i++) ProcessCar(cars[i]); } } Cannot use foreach since array is only partially filled

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-17 Array Limitations

 Arrays are typically allocated dynamically on the heap But …  Logically, their size is fixed once allocated • Often, this means we are wasting memory • But on occasion, it means we won’t have enough ◦ Might have to write expand/copy code  Array behavior does not match collections found in the real world • A queue of passengers • A list of groceries • A deck of cards

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-18 .NET Collections Overview

 .NET Framework comes with a comprehensive set of collections • Can usually find one that matches the problem we are trying to solve  There are two categories of collection • Heterogeneous: holds any kind of object ◦ Reference types by casting ◦ Value types by boxing ◦ In System.Collections namespace • Generic: constructed to hold only objects of a specific type ◦ In System.Collections.Generic namespace

 In either case, the behavior of a collection is independent of what it contains • A queue is a queue is a queue

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-19 ArrayList

 The freight-train example would be easier with an ArrayList • Similar to an array, but one that expands at runtime as needed • Freight cars are up-cast to object references using System.Collections; namespace Trains Must construct an { instance just like all public class FreightTrain other classes we use { … other fields … private ArrayList cars = new ArrayList(); No counter needed—it public void AddCar(FreightCar c) keeps count { cars.Add(c); Just add the freight car—no } copy and expand public void ProcessAllCars() Can use foreach { foreach (FreightCar car in cars) ProcessCar(car); //for (int i = 0; i < cars.Count; i++) // ProcessCar((FreightCar)cars[i]); } } } Can still index, but a cast is required

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-20 The Problem With Non-Generic Collections

• What would happen if the developer made the following mistake? using System.Collections; namespace Trains { public class FreightTrain { … other fields … private ArrayList cars = new ArrayList();

public void AddCar(FreightCar c) { cars.Add(c); cars.Add(new KitchenSink()); A programming mistake } public void ProcessAllCars() { foreach (FreightCar car in cars) ProcessCar(car); } } What happens here when } we hit the kitchen sink?

 Heterogeneous collections are rarely used in comparison to generic

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-21 Generic List

 There is no generic ArrayList—it is just a List • Can only put an object of the given type into a generic using System.Collections.Generic; namespace Trains { public class FreightTrain Can only hold freight cars { … other fields … private List cars = new List();

public void AddCar(FreightCar c) { cars.Add(c); What would happen here now? //cars.Add(new KitchenSink()); } public void ProcessAllCars() { foreach (FreightCar car in cars) ProcessCar(car); //for (int i = 0; i < cars.Count; i++) // ProcessCar(cars[i]); } } No cast required when indexing }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-22 Queues and Stacks

 Typical “real world” collections include queues and stacks using System.Collections.Generic; namespace CollectionSamples { public class StackSample using System.Collections.Generic; { namespace CollectionSamples public static void Main() { { public class QueueSample Stack s; { s = new Stack(); public static void Main() s.Push("Sammy"); { s.Push("Dean"); Queue q; s.Push("Frank"); q = new Queue(); while(s.Count > 0) q.Enqueue("Sammy"); Console.WriteLine(s.Pop()); q.Enqueue("Dean"); } Frank } q.Enqueue("Frank"); Dean  Stack output while(q.Count > 0) } Sammy Console.WriteLine(q.Dequeue()); } Sammy } Dean  Queue output } Frank

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-23 Dictionary

 Often, a “keyed” structure is needed—Dictionary is efficient and easy namespace Train { public class FreightCar Unique identifier { … other fields … private readonly string roadNumber; … constructors and other methods … public string RoadNumber { get{return roadNumber;} Both the key and the using System.Collections.Generic; value are explicit } public static void Main() } { } Dictionary carTable; carTable = new Dictionary(); FreightCar f1 = new FreightCar("T11", …); carTable.Add(f1.RoadNumber, f1); … repeat for many freight cars … Store each car using the road number as the key FreightCar x = carTable["T11"]; } Can get the car by its road number

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-24 Chapter Contents

• .NET Framework

• I/O Classes

• Collection Classes  ASP.NET Framework

• Hands-On Exercise 5.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-25 State Management

 Both Windows Forms and ASP.NET make liberal use of collection classes  In particular, ASP.NET uses them for state management • Needed because web pages are inherently multithreaded • Many requests for the same page can be made by different users at the same time  Must reestablish from request to request the browser’s context • Usually done in the Page_Load event  The context of the web controls and the page itself are remembered in a unique viewstate object • Managed automatically and transparently

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-26 Using the Session Object

 Various state-control collections that we can use are automatically created • Application and Cache to save global information • Session object to save user-specific information  The Session, for example, is a specialized dictionary collection public class SomeApp : System.Web.UI.Page { private BankAccount acct;

private void Page_Load(object sender, System.EventArgs e) { acct = (BankAccount)Session["acct"]; // Try to get user's data if (acct == null) // Has user been here? { acct = new BankAccount(…); // No, create new account. Session["acct"] = acct; // Remember for next time … other statements … } } … other methods and fields… }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-27 Chapter Contents

• .NET Framework

• I/O Classes

• Collection Classes

• ASP.NET Framework  Hands-On Exercise 5.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-28 Hands-On Exercise 5.1

In your Exercise Manual, please refer to Hands-On Exercise 5.1: Associations and Collections

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-29 Chapter Contents

• .NET Framework

• I/O Classes

• Collection Classes

• ASP.NET Framework

• Hands-On Exercise 5.1  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-30 Review Questions

What is the difference between a generic collection and a nongeneric collection?

What attribute is necessary for a class to support being serialized?

What two parameters must be provided when adding an object to a Dictionary collection?

What is the general syntax to declare and create a generic list of Thing?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-31 Chapter Summary

In this chapter, we have discussed  The .NET Framework  Utility classes  Basic I/O classes  Serialization  ASP.NET Framework  Collection classes

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-32 Chapter 6

Interfaces and Polymorphism Chapter Objectives

This chapter explores the modern use of C# as an object-oriented language In particular, we will discuss  Overriding and polymorphism  Abstract classes • The separation of implementation from interface  Interfaces  The IEnumerable interface • To enable foreach loops and extension methods

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-2 Chapter Contents

 Overriding and Polymorphism

• Hands-On Exercise 6.1

• Abstract Classes

• Interfaces

• The IEnumerable Interface

• Hands-On Exercise 6.2

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-3 Tanker Analysis

 In the course exercises, we have overridden the ToString() method • This is an example of polymorphism • When a derived class should do something differently than its base class  Recall our freight cars—most are cubical, so a “volume” property could be generally calculated as length x width x height

What is wrong with this for a tanker?

Gondola Boxcar Tanker

Watch out—not all modern tankers are cylindrical • Some look very much like boxcars

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-4 Declaring virtual/override Methods

 If we derive Tanker from FreightCar, it would be necessary to override the Volume property namespace Trains { public class FreightCar Use virtual here { private int length, width, height; to indicate that an private readonly string roadNumber; override is allowed public int Length { get { return length; }} … constructors and other methods …

public virtual double Volume namespace Trains { { get { return length * width * height; } public class Tanker : FreightCar } { } } public double Radius { get; set; } Use override here to … other methods … indicate we are replacing it

public override double Volume { get { if (Radius == 0) return base.Volume; // Not cylindrical! return Math.PI * Radius * Radius * Length; } } } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-5 Using the Tanker Class

 Now we can use the Tanker-specific volume calculation

using System; namespace Trains { public class TrainClient { public static void Main() { FreightCar fc = new FreightCar("Box 51", 40, 10, 10); Tanker tc = new Tanker("Tank 22", 40, 10, 10, 5); double fv = fc.Volume; // Get freight car volume Create a double tv = tc.Volume; // Get tanker volume tanker with Console.WriteLine("Freight volume = {0,7:N1}", fv); radius of 5 Console.WriteLine("Tanker volume = {0,7:N1}", tv); … } } } Freight volume = 4,000.0 Tanker volume = 3,141.6 Program output

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-6 Derived Objects as Base Objects

 When a class is derived, C# allows a base-class reference to refer to a derived-class object • All that is actually stored in memory for an object is its data  A derived class usually has some incremental behavior • Can be accessed polymorphically through the base reference

DerivedObject … base class data …

… derived class BaseReference data …

BaseObject … base class data …

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-7 Using FreightCar References

 Polymorphism saves time because it means we don’t have to determine an object’s type to obtain the correct behavior

using System; Get a bunch of cars; we don’t know (and namespace Trains don’t care) if they are Tankers or some { other type of FreightCar public class FreightTrain { public static void Main() { List cars = customer.GetCars(); double totalVolume = 0.0; foreach (FreightCar car in cars) totalVolume += car.Volume; } } Regardless of the type } of car, we will get the correct volume

This is especially useful when using arrays and collections of like objects in an inheritance hierarchy

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-8 Casting

 However, we must cast back to a Tanker reference to obtain Tanker-specific behavior  The Radius property is not part of the interface of a FreightCar • Must ask for the radius only for Tankers ◦ Or objects inherited from Tankers  Can use the is operator and a cast for this purpose

public static void Main() { FreightCar car = customer.GetCar(); … statements … if (car is Tanker)  Is it a tanker? { Tanker tank = (Tanker) car;  Cast int rad = tank.Radius; … statements … } } Note that we use a Tanker reference

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-9 as Operator

 An alternative to the is operator and casting is the as operator  Can be used only with reference types  Unlike casting, as returns a null rather than throwing an exception when the types do not match

public static void Main() { Tanker tank = customer.GetCar() as Tanker;

if (tank != null) { int rad = tank.Radius; If not a Tanker (or something inherited from … statements … Tanker), then it will be null } }

 This is especially useful with collections and arrays of type object

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-10 Chapter Contents

• Overriding and Polymorphism  Hands-On Exercise 6.1

• Abstract Classes

• Interfaces

• The IEnumerable Interface

• Hands-On Exercise 6.2

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-11 Hands-On Exercise 6.1

In your Exercise Manual, please refer to Hands-On Exercise 6.1: Down-Casting

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-12 Chapter Contents

• Overriding and Polymorphism

• Hands-On Exercise 6.1  Abstract Classes

• Interfaces

• The IEnumerable Interface

• Hands-On Exercise 6.2

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-13 Abstract Classes

 Abstract classes represent ideas or concepts • For example: What are shapes? What are mammals?  Use of an abstract class is by inheritance only—no direct object instances • Access to derived classes is often done using polymorphism ◦ The abstract class establishes the interface ◦ The derived class provides the implementation

 Abstract classes can have abstract methods • Forces implementation by the derived class  The opposite of an abstract class is a sealed class • Rarely used

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-14 Abstract Class Syntax

 For a class to be abstract, we simply declare it as abstract

public abstract class Shape Class itself declared abstract { Some methods and properties private double x; // Location private double y; declared abstract … constructors and other methods … public class Rectangle : Shape public abstract double Area {get;} { public abstract void Draw(); private double length; public double GetX() { return x; } private double width; public double GetY() { return y; } … constructors and other methods … } public override double Area public class Circle : Shape { { get{return length * width;} private double radius; } … constructors and other methods … public override void Draw() { … } public override double Area } { get{return Math.PI * radius * radius;} Abstract methods and } properties must be implemented public override void Draw(){ … } } in derived class

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-15 Using Abstract Classes

 Abstract classes cannot be instantiated • But their references can point to a derived concrete object • And their methods and properties called polymorphically

public void Main() { // Shape s = new Shape(); // Won't compile

Shape s = new Circle(...); // Can reference a circle double a = s.Area; // Get the area ... }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-16 Chapter Contents

• Overriding and Polymorphism

• Hands-On Exercise 6.1

• Abstract Classes  Interfaces

• The IEnumerable Interface

• Hands-On Exercise 6.2

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-17 About Interfaces

 An abstract class with no implementation leaves only the interface • A list of unimplemented methods and properties  This introduces a useful way of viewing objects • Not by what they are but by what they can do ◦ Identification by behavior, not type

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-18 UML Notation

Which of the following should realize IWearable? IRentable?

Product <> <> Inventory IWearable IRentable has string upc … 1..* Sell() … string UPC{get} PutOn() CheckOut() CheckIn() Dashed means realization of an interface

Book Soda Axe Tuxedo … … … …

… … Chop() …

BubbleGum Shoe Coffee … Shine() … … … …

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-19 Syntax and Usage

 The C# syntax is similar to inheritance • By convention, interfaces in .NET start with a capital I public abstract class Product public interface IRentable { { private string upc; void CheckOut(); … void CheckIn(); public void Sell() {…} public string UPC } public interface IWearable { { get{return upc;} void PutOn(); } } } Specifies an public class Shoe : Product, IWearable interface { public void PutOn() { … } public void Shine() { … } } public class Tuxedo : Product, IWearable, IRentable { public void PutOn() { … } public void CheckOut() { … } public void CheckIn() { … } Specifies the implementation } (realization) of the interface

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-20 Identifying Behavior

 Now we can identify and use inventory items based on their behavior

namespace Inventory { public class ProductHandler { public static void Main() // Start here. { Product[] inventory = ReadAllProducts(); // Load inventory foreach (Product p in inventory) // Check it all… { if (p is IWearable) // Is it wearable? { IWearable w = (IWearable) p; // Yes, so we can … w.PutOn(); // … put it on. } if (p is IRentable) // Is it rentable? { AssignToRentalDept((IRentable)p); // Allocate it. } } } public static void AssignToRentalDept(IRentable item) { ... } } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-21 About Interfaces

 An interface is similar to inheritance • Uses the same C# syntax to specify • A reference of the interface type can refer to any object that implements that interface But …  The semantics of interface implementation are for a different purpose • Identification based on behavior vs. extension of existing class • Useful to think of it as “exposing an interface”  C# supports • Single inheritance • Realization of multiple interfaces  There are often both generic and non-generic versions of interfaces

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-22 Chapter Contents

• Overriding and Polymorphism

• Hands-On Exercise 6.1

• Abstract Classes

• Interfaces  The IEnumerable Interface

• Hands-On Exercise 6.2

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-23 Enumerating With IEnumerable

 IEnumerable is one of the most common interfaces used in .NET • It provides two very useful capabilities 1. Allows foreach loops to be used on classes that appear as collections • That is, collections within the implementing class can be enumerated for the type specified by T • For example, IEnumerable would permit client code to loop through all the Transactions in a BankAccount

2. Supports numerous extension methods that can be used to manipulate the collection Such as Count(), which will determine the number of items Or Reverse(), which will reverse the order of items

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-24 IEnumerable Example

 For example, a BankAccount class might hold a list of transactions through which the client might want to count or loop Realize the interface public class BankAccount : IEnumerable { private List tList = new List(); public void Post(Transaction trx) { tList.Add(trx); } … other fields and methods … public IEnumerator GetEnumerator() Primary method { required by the return tList.GetEnumerator(); interface contract } } public static void Main() { Can use the Count() BankAccount acct = new BankAccount(…); extension method … post transactions … Console.WriteLine("Transactions: " + acct.Count(); foreach (Transaction trx in acct) Console.WriteLine(trx); } Can use a foreach

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-25 About Extension Methods

 Extension methods are actually static methods used at the object level • Shown by IntelliSense as member functions  Commonly used in the .NET library to provide functionality to any class that implements IEnumerable • So that the same identical logic would not have to be repeated in different collection classes  Most also return IEnumerable so they can be chained • acct.Reverse().Take(2) would enumerate only the last two transactions  They do not usually change the state of the object’s items or collection • For example, acct.Reverse() would reverse the enumeration ◦ The actual items in the collection would stay in the same order

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-26 Using Extension Methods

 What would each of the following yield? • Assumes Deposit and Check are inherited from Transaction • Transaction.ToString() outputs the amount of the transaction public static void Main() { BankAccount acct = new BankAccount(…); acct.Post(new Deposit(100.00M)); acct.Post(new Check(50.00M)); acct.Post(new Check(13.12M)); acct.Post(new Deposit(200.00M));

Console.WriteLine(acct.Count()); //______

foreach (Transaction trx in acct.Reverse().Take(2)) Console.WriteLine(trx); // ______

Transaction trx = acct.Skip(1).First(); Console.WriteLine(trx); // ______}

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-27 Chapter Contents

• Overriding and Polymorphism

• Hands-On Exercise 6.1

• Abstract Classes

• Interfaces

• The IEnumerable Interface  Hands-On Exercise 6.2

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-28 Hands-On Exercise 6.2

In your Exercise Manual, please refer to Hands-On Exercise 6.2: Implementing Interfaces

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-29 Chapter Contents

• Overriding and Polymorphism

• Hands-On Exercise 6.1

• Abstract Classes

• Interfaces

• The IEnumerable Interface

• Hands-On Exercise 6.2  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-30 Review Questions

What is the purpose of an interface?

What key words must be used to implement a polymorphic method in a derived class when inheriting from a base class?

What is an abstract method? What is the only type of class that can have an abstract method in it?

What can you do to create a polymorphic method in a derived class if the base-class developer did not declare it to be virtual?

Since all classes are inherited from object, would the statement object o = "Hello"; be legal?  Yes  No

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-31 Polymorphism Drill

Given the indicated inheritance hierarchy, select the method that is called for each of the following code sequences; indicate why and which criteria:

Base b = new Base(); // Base to a Base b.do1(); // Base b.do1(5); // b.do2(); // b.do3(); // 1 do1() 2 do1(int i) Derived d = new Derived(); // Derived to derived do2() 3 d.do1(); // d.do1(5); // d.do2(); // Derived d.do3(); //

Base b1 = new Derived(); // Base to derived 4 do2() b1.do1(); // 5 do3() b1.do1(5); // b1.do2(); // b1.do3(); //

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-32 Chapter Summary

This chapter has explored the modern use of C# as an object-oriented language In particular, we have discussed  Overriding and polymorphism  Abstract classes • The separation of implementation from interface  Interfaces  The IEnumerable interface • To enable foreach loops and extension methods

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-33

Chapter 7

Writing .NET Components Chapter Objectives

In this chapter, we will learn  How to create .NET components that can be used by • Other programs written in other CLR languages • Other programs written in legacy non-CLR languages (and vice versa) • Other C# programs

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-2 Chapter Contents

 Writing .NET Components

• Component Compatibility

• Hands-On Exercise 7.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-3 COOL

 The original name of C# was COOL • For the Component Object Oriented Language  Suggesting that component infrastructure was built directly into the language • You’ve been building components transparently since the start of the course  For example, namespaces imply the component filename  C# data types are inherently compliant with the Common Language Specification (CLS) • For example, data types map one-to-one (double = System.Double)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-4 Writing .NET Components in C#

 Administration and deployment are automatic • Code does not need to be aware that it is a component ◦ No administration statements • Component does not need to be registered in a central repository • Versioning is automatic  Component creation is achieved by • Following some simple guidelines when writing your code ◦ Most are good practices and should be done anyway • Compiling your program as a component into a class library • Deploying for use by building assemblies

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-5 C# Component Guidelines

 The component classes to be exposed must be public • Nonpublic classes should be left internal, the default  Must follow Microsoft namespace and component naming guidelines • Use initial-cap notation (CreditLimit, not credit_limit)  Exposed (public, protected) parts must be CLS-compliant • Basically means the lowest common features available to all .NET languages ◦ No use of unsigned ◦ No use of identifiers that differ only by case ◦ No functionality only available as an operator overload ◦ No unsafe code (see Appendix B for more on unsafe code)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-6 Remote and COM Compatibility

 Components that will be used remotely must inherit from System.MarshalByRefObject

 Components that will be made available as COM components must • Inherit from System.ComponentModel.Component ◦ Which itself inherits from System.MarshalByRefObject • Have their COM visible property set in the library’s properties

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-7 Chapter Contents

• Writing .NET Components  Component Compatibility

• Hands-On Exercise 7.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-8 Cross-Language Components

 Transparent cross-language capability is achieved by using components • Any CLS-compliant language should work with any other CLS-compliant language • There is no record in the assembly as to what the source language was  There are many known CLS-compliant languages, including • Visual Basic (VB) ◦ Was called VB.NET, now just called VB (again) • Visual F# • Other third-party languages (COBOL, RPG, Smalltalk)  A special case is C++/CLI • Generally called “Managed C++” • ECMA standard evolved from earlier Microsoft-specific enhancements • C++/CLI works like any other .NET language, but it can also directly interface to standard C++ native binaries

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-9 Optional Instructor Demonstration Demo

 Your instructor might choose to show how our C# card library can be accessed from VB • This is an optional demo  Note that even though both VB and C# generate CIL when compiled, the cross-language feature could not be achieved without using the .NET component model

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-10 Backward Compatibility

 COM legacy components are plentiful • This is the most common inter-infrastructure need  Visual Studio supports both forward and backward compatibility with COM  To create a COM component from a .NET component 1. In AssemblyInfo.cs, set CLSCompliant and ComVisible to true 2. Digitally sign using the sn utility 3. Deploy as a shared assembly—use gacutil/i to insert into the GAC 4. Register the .NET component as a COM component in the Windows registry using the RegAsm.exe tool 5. Consume like any other COM component  To use a COM component in a .NET program 1. Install and register the COM component in the standard fashion 2. Import the COM component into the Visual Studio solution – Conversion to .NET compatibility is automatic 3. Use the result like any other .NET component

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-11 Chapter Contents

• Writing .NET Components

• Component Compatibility  Hands-On Exercise 7.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-12 Hands-On Exercise 7.1

In your Exercise Manual, please refer to Hands-On Exercise 7.1a: Adding Desktop Card Images—COM Components or Hands-On Exercise 7.1b: Adding Desktop Card Images—Image List Component or Hands-On Exercise 7.1c: Adding Web Card Images—Image Component

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-13 Chapter Contents

• Writing .NET Components

• Component Compatibility

• Hands-On Exercise 7.1  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-14 Review Questions

Compare and contrast COM components and .NET components:

Can .NET components call COM components? Vice versa?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-15 Chapter Summary

In this chapter, we have learned  How to create .NET components that can be used by • Other programs written in other CLR languages • Other programs written in legacy non-CLR languages (and vice versa) • Other C# programs

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-16 Chapter 8

Accessing Databases Chapter Objectives

In this chapter, we will  Continue the evolution of our application by considering the data access layer

View Rules Data

 Examine the ADO.NET DataSet class  Discuss the LINQ vocabulary of C#  Access relational databases using the Entity Framework

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-2 Chapter Contents

 Object-Relational Mapping

• ADO.NET Overview

• Language Integrated Query (LINQ)

• Accessing a Database With LINQ/EF

• O/R Designer

• Updating a Database With LINQ/EF

• Hands-On Exercise 8.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-3 About Relational Databases

 A relational database can “relate” data stored in different tables • A table is divided into rows (records) and columns (fields) • Usually, one column contains a primary key ◦ A unique piece of information, so a record can be identified • Tables can be joined together to be viewed like a single table Primary key ◦ Related by a foreign key

Foreign key Artist Table AID FirstName LastName Age Song Table 1 Paul Williams 51 SID Title Artist 2 Paul McCartney 55 1 Yesterday 2 3 YoYo Ma 34 2 Ring the Bells 4 4 Sean Smith 29 …… … 5 John Williams 66 6 Paul Simon 44

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-4 About SQL

 Relational databases have traditionally been accessed non-procedurally using SQL • An ANSI-standard language invented in the 1970s

 For example: SELECT Age FROM Artist WHERE FirstName = 'Paul'

DELETE FROM Artist WHERE Age < 50

UPDATE Artist SET Age = 51 WHERE AID=3

INSERT INTO Song (Title, Artist) VALUES ('Bob Minor', 4)

 Often enhanced with some database-specific procedural capability • Such as Transact-SQL for SQL Server or PL-SQL for Oracle

ANSI = American National Standards Institute

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-5 Oil and Water

 Unfortunately, the relational model and the object-oriented model are different paradigms  Like oil and water • They don’t really mix!  Can coexist nicely if you just keep them independent • Separated from one another by interface  One must be mapped to the other

OO concept RDBMS implementation Class Table Object Row Field Column Object identifier Primary Key Association Foreign key

RDBMS = relational database management system

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-6 Mapping Classes to Tables

 A class that is mapped from a relational table is called an entity class

Song SID Title Artist Song Title

Foreign key

*

1 Artist Artist AID FirstName LastName Age FirstName LastName Age

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-7 Artist Entity Class

 The entity class to hold artist data might look like this:

public class Artist { public int AID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public void HaveBirthday() { Age += 1; } public override string ToString() { return FirstName + " " + LastName + " " + Age; } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-8 Chapter Contents

• Object-Relational Mapping  ADO.NET Overview

• Language Integrated Query (LINQ)

• Accessing a Database With LINQ/EF

• O/R Designer

• Updating a Database With LINQ/EF

• Hands-On Exercise 8.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-9 ADO.NET Introduction

 Traditionally, the ADO.NET library has been used to provide access to relational databases  Has classes to hold, read, and write relational data; issue SQL statements; and manage transactions  There are separate provider libraries • Vendor-neutral OLE DB/ODBC supports essentially any database • Vendor-specific for SQL Server and Oracle

ODBC = open database connectivity OLE DB = object linking and embedding database

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-10 ADO.NET Choices

ADO.NET is designed to be used in a number of different ways 1. Automated data binding in a GUI program • Wizard-generated DataSource maps database table to visual controls • Supported for both Windows.Forms and Web.UI namespaces 2. Using a wizard-generated, in-memory collection of tables called a DataSet • Access is done via the DataSet rather than by direct SQL statements • Typically contains a “snapshot” of some or all of the data 3. Programmatically using a set of database manipulation classes • Developer manually writes SQL commands and transaction schemes • DataReader provides a forward-only, client-side cursor for pulling single records at a time 4. As a hidden layer underneath the data access providers for LINQ • A modern and more flexible way to achieve 2 and 3

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-11 Programming DataSets

 A DataSet object is really an in-memory database • Usually a subset of an on-disk database • Composed of collections of tables, columns, and rows DataRow DataTable DataRow DataRow DataSet DataTable DataTable

DataColumn DataColumn  Works with an associated DataAdapter • Contains the SQL • Fill method loads data into the DataSet • Update method writes it back  Typically, a DataSet is generated using the design wizard in Visual Studio

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-12 Data Access Architecture

 DataSets have often been used to write data-accessor classes • Keeps data access separate from the object-oriented business logic  This is a highly desirable architecture for most applications!

{ Data accessor { ADO.NET converts tables into Database } lists of objects and & SQL } tables handles all reading and updating In memory tabular view

Data access layer Data access layer Business rules layer Business rules layer Object

Middle-tier client Object code knows nothing Object about database or { ADO.NET; uses { generic lists of } } entity objects Generic list

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-13 Programming a Data Accessor Using a DataSet

 A data accessor can use a DataSet to load records from a database and return a collection of objects  The steps to do this 1. Use the design wizard in Visual Studio to generate a DataSet class, specifying what tables it should hold and SQL it should use 2. Create a SQL query string, filling in substrings for query arguments 3. Assign the query to the data adaptor’s select command text 4. Fill the data adaptor (access the database) 5. Select a data table from the resulting dataset 6. Iterate over the rows of the data table a. Extract fields from the data row using an indexer b. Construct a new entity object using those fields c. Add the entity object to the collection 7. Return the collection 8. Client code uses the collection in a pleasant, object-oriented fashion  See code example on next slide

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-14 Programming a Data Accessor Using a DataSet

 A data adapter method to get artists by first name, ordered by last name • Assumes dsArtist is a DataSet wizard-generated to contain artist data

public static List GetByFirstName(string firstName) { string query = "SELECT * FROM Artist "; query += string.Format("WHERE FirstName = '{0}' ", firstName); query += "ORDER BY LastName"; sqlDataAdapter1.SelectCommand.CommandText = query; sqlDataAdapter1.Fill(dsArtist); // Get artist data DataTable dt = dsArtist.Tables[0]; // Get only table Listartists = new List(); // Construct the list foreach (DataRow dr in dt.Rows) // Loop through rows { Artist a = new Artist() a.FirstName = firstName; a.AID = (int)dr["AID"]; a.LastName = (string)dr["LastName"]; a.Age = (int)dr["Age"]; artists.Add(a); } List pauls = return artists; MusicData.GetByFirstName("Paul"); } foreach (Artist paul in pauls) paul.HaveBirthday();

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-15 Chapter Contents

• Object-Relational Mapping

• ADO.NET Overview  Language Integrated Query (LINQ)

• Accessing a Database With LINQ/EF

• O/R Designer

• Updating a Database With LINQ/EF

• Hands-On Exercise 8.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-16 The Need for Declarative Data Access

 DataSets and the related ADO.NET classes require the intermingling of two different syntaxes: C# and SQL  More importantly, the approach is flow-centric—the program must • Control when the data should be fetched and saved • Decide when to open and close connections • Make sure connections do not get “dangled” (left open) • Manually optimize for partial record updates • Etc.  LINQ establishes a declarative approach to data access • Specify what data is needed • Framework will essentially take care of the connections, flow, and the rest  Has the potential to minimize or eliminate direct use of ADO.NET and SQL • Easier to write and more efficient

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-17 Specifically, What Is LINQ?

 LINQ is a vocabulary of query keywords built into the C# language core • Syntactically and semantically different from SQL ◦ from, where, orderby, select, join, numerous others

 In and of themselves, the LINQ keywords have nothing to do with data access • Can be used for many general-purpose chores Must be paired with a provider to access a database

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-18 LINQ to Objects Example

 In this example, LINQ is used to “query” an array • Find even numbers and sort from highest to lowest

public static void Main() // Output sorted even numbers only { int[] nums = new int[] { 14, 11, 222, 535, -18, 105 }; IEnumerable result = from n in nums where ((n % 2) == 0) orderby n descending select n; foreach (int i in result) Console.WriteLine(i); } 222 14 -18  The result of a query expression is of type IEnumerable • Can be used directly in a foreach Output

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-19 Anatomy of a Query

 Each query begins with a from statement of the form from range variable in data source

 Range variable is an object scoped locally within the query • Type is implicit; the same as the entities contained in the data source • Subsequent keywords within the query work in terms of the range variable  Data source is any IQueryable object on which the query will be run • Arrays, database tables, XML documents, and most library collection classes implement IQueryable

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-20 Writing Queries

 Write a query to select people who have the last name “Smith,” then order them, descending alphabetically List people = new List { "David Severn", "Peter King", "Michael S. Terrazas", "Sean Smith", "Richard Howells", "T. J. Smithson", "David H. Smith", "Masaaki Mizuno", "Vladimir Khazin", "Beatrice R. Smith", "Elizabeth Smyth" };

 Modify the query to include only those “Smiths” who have a middle initial

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-21 Query Methods

 The C# LINQ vocabulary has a modest set of key words • The nature of C# does not require more  Extra capability provided by special extension query methods such as First(), Distinct(), Reverse(), Take(), Skip(), and many more  To get all of the first names of artists, without repeats, use: IEnumerable names = from artist in db.Artist orderby artist.FirstName select artist.FirstName; names = names.Distinct(); IEnumerable names = (from artist in db.Artist Or: orderby artist.FirstName select artist.FirstName).Distinct();

 Modify the query on the previous slide to get only the second and third entities

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-22 Explicit and Implicit Declarations

 C# is a strongly typed language • Variables must be initialized or assigned before they are used • Both of the following would be valid: Assignment string inCur; inCur = "USD"; string outCur = "EUR"; Initialization  Variables can be implicitly typed using the var keyword • However, this is only valid if initialization is done during declaration

var aStr; Not valid aStr = "ABC"; var eStr = "EFG"; Valid Note that implicit typing is still strong typing

Samples\ImplicitTyping

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-23 Explicit and Implicit Declarations

What are the data types of the following implicit declarations? 1. var x = 1.26m; ______2. var y = '\u02A5'; ______3. var z = 1l; ______4. var a = new BankAccount(); ______5. var b; ______

 It is common to use implicit typing with LINQ • But general use might make a program less readable

var names = (from artist in db.Artist orderby artist.FirstName select artist.FirstName).Distinct();

What is the data type of names in the forgoing?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-24 Chapter Contents

• Object-Relational Mapping

• ADO.NET Overview

• Language Integrated Query (LINQ)  Accessing a Database With LINQ/EF

• O/R Designer

• Updating a Database With LINQ/EF

• Hands-On Exercise 8.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-25 LINQ Providers

 Frameworks delivering IQueryable data sources are called providers • LINQ to Objects is used for arrays and collections ◦ What we used in the previous examples • LINQ to XML used for XML document processing • LINQ to DataSets simplifies working with ADO.NET  Providers that access databases are • LINQ to SQL for SQL Server (was first but largely replaced by LINQ/EF) • LINQ to Entities (LINQ/EF) is for any database  LINQ/EF and LINQ to SQL are very similar in concept; they both • Are built on top of ADO.NET • Do all connection and flow management automatically • Seek to make the database appear as a “gigantic collection of entity objects” • Their internal implementation and usage details are very different  Let’s modify the artist data accessor shown on slide 8-15 to use LINQ/EF rather than ADO.NET and DataSets

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-26 Data Layer Architecture With LINQ/EF

 LINQ/EF keeps entity objects logically attached to the database • They track loading and changes automatically

 This greatly simplifies the data accessor logic Mapping code { in LINQ/EF { converts to } lists of objects Database } tables

Data access layer Data access layer Business rules layer Business rules layer Object Object Object { {

} } Generic list

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-27 Data Accessor Using LINQ/EF

 Method to get artists by first name, sorted by last name using LINQ/EF • Assumes db is a wizard-generated DbContext

public class MusicData { ... public static List GetByFirstName(string firstName) { Artist table in music database var artists = from artist in db.Artists where artist.FirstName == firstName orderby artist.LastName select artist; return artists.ToList(); } List pauls = MusicData.GetByFirstName("Paul"); } foreach (Artist paul in pauls) Console.WriteLine(paul);

 This is much simpler than the DataSet equivalent shown on slide 8-15

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-28 Chapter Contents

• Object-Relational Mapping

• ADO.NET Overview

• Language Integrated Query (LINQ)

• Accessing a Database With LINQ/EF  O/R Designer

• Updating a Database With LINQ/EF

• Hands-On Exercise 8.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-29 Object Relational (O/R) Designer

 LINQ to SQL and LINQ/EF come with visual O/R Design tools included with Visual Studio • Does for databases what the original VB did for graphical user interfaces  Uses visual techniques to generate entity classes from database tables • LINQ to SQL specifies the mapping using [Table] and [Column] attributes • LINQ/EF incorporates the mapping by inheritance from the entity framework Assumes database has been properly designed and implemented  LINQ/EF also supports generating a database from “plain old C# objects” • Sometimes called POCO

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-30 EF Inheritance Hierarchy

 The O/R Designer for LINQ/EF will automatically generate an Entity Data Model (EDM) in an .edmx file that contains • Entity classes that match the tables in the database • Associations between the generated classes based on their foreign keys • A database context (DbContext) to automatically analyze and optimize queries, manage connections, and coordinate the data flow

DbContext The Music EDM would map something like this:

… Automatically creates an entity class for each mapped database table MusicEntities Exposes tables by their names so they can be accessed directly as if they … Artist and Song classes … were a “collection of entity objects” Artist: IQueryable Song: IQueryable … SaveChanges() Provides methods for saving changes and adding/deleting entities

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-31 Connection Strings

 Connection strings specify how to find and attach to a database • Regardless of how the database is deployed  They are typically placed in the app.config or web.config file so they can be changed or manipulated easily outside of the application • The only change necessary to switch from development to production  LINQ/EF requires a connection string that contains not only the database parameters, but also the mapping parameters • The DB connection string is embedded inside the EF connection string  The O/R Designer will make a good estimate at automatically generating connection strings, but… • It is always a good idea to review the results • Many mysterious problems occur because of incorrect connection strings

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-32 Optional Instructor Demonstration Demo

 Your instructor might choose to demonstrate the O/R Designer using LINQ/EF as an example • Or let you discover how cool it is on your own during the exercise  Please be sure to notice • The generated entity classes in the .edmx file • That the MusicEntities class can be used to access the database tables as if they were a “collection of entity objects”  Completed demo is in C:\Course\419\Do Now Demo\Demo81

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-33 Chapter Contents

• Object-Relational Mapping

• ADO.NET Overview

• Language Integrated Query (LINQ)

• Accessing a Database With LINQ/EF

• O/R Designer  Updating a Database With LINQ/EF

• Hands-On Exercise 8.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-34 partial Classes

 In general, it is highly desirable to be able to manipulate the LINQ/EF generated entity classes in a standard, object-oriented fashion  Generated entity classes should not be edited directly • Changes would be lost if the database were remapped • Sources are not generated to be editable by the EF 5 O/R Designer  partial classes can be used to add functionality to the generated entities • Very similar to what is done with Windows Forms or ASP.NET pages

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-35 partial Classes

 For example:

public partial class Artist Facsimile of what the O/R Designer { will generate ... other columns ... public int Age { get; set; }} } public partial class Artist { public void HaveBirthday() { Age += 1; } Our partial class to public override string ToString() { ... } add the necessary methods }

 Watch out! In EF 5, the second partial class segment must have a filename that is different from the O/R generated one • Convention is to add the word “Additions” as in ArtistAdditions.cs

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-36 Updating the Database

 Because in-memory entity objects are still “attached” to their row in the database, updating is easy • Simply use the entity object in a standard object-oriented fashion • When done, write out changes using db.SaveChanges() public class MusicData { private static MusicEntities db = new MusicEntities(); public static List GetByFirstName(string firstName) { ... As before ... } public static void SaveChanges() { db.SaveChanges(); } }

 Example: All artists named Paul have a birthday

List pauls = MusicData.GetByFirstName("Paul"); foreach (Artist paul in pauls) paul.HaveBirthday(); MusicData.SaveChanges();

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-37 Putting It All Together

 The complete logic to implement the data accessor for the music database would look something like this:

public class MusicData { private static MusicEntities db = new MusicEntities(); public static List GetByFirstName(string firstName) { var artists = from artist in db.Artist where artist.FirstName == firstName orderby artist.LastName select artist; return artists.ToList(); } public static void SaveChanges() { db.SaveChanges(); } public static void Delete(Artist a) { db.Artists.Delete(a); } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-38 Chapter Contents

• Object-Relational Mapping

• ADO.NET Overview

• Language Integrated Query (LINQ)

• Accessing a Database With LINQ/EF

• O/R Designer

• Updating a Database With LINQ/EF  Hands-On Exercise 8.1

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-39 Hands-On Exercise 8.1

In your Exercise Manual, please refer to Hands-On Exercise 8.1: Using LINQ/EF

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-40 Chapter Contents

• Object-Relational Mapping

• ADO.NET Overview

• Language Integrated Query (LINQ)

• Accessing a Database With LINQ/EF

• O/R Designer

• Updating a Database With LINQ/EF

• Hands-On Exercise 8.1  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-41 Review Questions

List four LINQ keywords used in a query:

What is a DataSet?

How does LINQ/EF relate an entity class to a table?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-42 Chapter Summary

In this chapter, we have  Continued the evolution of our application by considering the data access layer  Examined the ADO.NET DataSet class  Discussed the LINQ vocabulary of C#  Accessed relational databases using the Entity Framework (EF) There is much more to learn about LINQ and the Entity Framework  For more information, see Course 973, Programming C# Extended Features 973

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-43

Chapter 9

Other C# Features Chapter Objectives

In this chapter, we will  Examine some useful C# syntax that is less commonly used • Symbolic operator overloading • Indexers • Initializers  Leverage language features that integrate C# and the CLI runtime • Delegates • Events • Lambda expressions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-2 Chapter Contents

 Initializers

• Symbolic Operators and Indexers

• Events and Delegates

• Lambda Expressions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-3 Object Initializers

 Object initializers are a convenient alternative to a constructor • Works for properties that have a public set

public class Instructor { public string Name { get; set; } public string Country { get; set; } } public void SomeMethod() Note: no constructor { Instructor i1 = new Instructor(); i1.Name = "Jole Jonikic"; Could just manually set i1.Country = "Sweden"; each property Instructor i2 = new Instructor { Name = "Luc Carité", Country = "France" }; ... } Object initializer syntax is more convenient

Course\419\Samples\ObjectInitializers

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-4 List and Dictionary Initializers

 Similarly, a list initializer is a convenient alternative to tedious calls to the Add(…) method ... List pilots = new List { "Neil Armstrong", "Jimmy Doolittle", "Douglas Bader" }; ...

 A dictionary initializer can use the convenient [key] notation ... Dictionary flightHours = new Dictionary { ["Neil Armstrong"] = 2281, ["Jimmy Doolittle"] = 3922, ["Douglas Bader"] = 5260 }; ...

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-5 Chapter Contents

• Initializers  Symbolic Operators and Indexers

• Events and Delegates

• Lambda Expressions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-6 Operator Overview

 In addition to methods and properties, a class can also have symbolic operators  A convenient alternate syntax to using methods • And very useful if writing a mathematical class  The operators that can be overloaded include • Most relational operators (==, !=, >, <, >=, <=) • Some unary operators (+, -, !, ++, --) • Some binary operators (+, -, *, /, %, &, |, ^, <<, >>)  The index operator [] cannot be overloaded in the C++ sense • But an indexer can be used for this purpose

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-7 Operator Method Definitions

 An overloaded operator definition is just a static method with a special signature, the format of which is: public static Type operatorOP(CLASS left, CLASS right)

• Where OP refers to the operator being overloaded • And CLASS is the class reference for which it is being overloaded  Assuming we overloaded the > operator for some class X, the statement if (x1 > x2) ...

is automagically converted by the compiler to if (X.operator>(x1, x2)) ...

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-8 Operator Overload Example

 Symbolic operators should be defined only if there is a true need for them • Such as mathematical types (which tend to be structures) public struct complex { Multiply operator public double real; public double imag; public static complex operator*(complex left, complex right) { complex result; result.real = left.real * right.real - left.imag * right.imag; result.imag = left.real * right.imag + left.imag * right.real; return result; } public override string ToString() { return "(" + real + "+" + imag + "i)"; } … other methods … } public void Main(string[] args) { complex c1; c1.real = 10.2; c1.imag = 4.6; complex c2; c2.real = 18.6; c2.imag = 21.11; complex c3 = c1 * c2; Console.WriteLine("c3 = " + c3); Use the multiply }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-9 Introduction to Indexers

 An indexer is very similar to a property but works like a symbolic operator • A syntax alternative to having “lookup” functions  Consider the transaction lookup function in the following bank account • It could be written as an indexer public class BankAccount { private Transaction[] transactions = ... … other fields and methods … Look up by public Transaction Lookup(string code) transaction code { foreach (Transaction trx in transactions) { if (trx.Code == code) return trx; } throw new ArgumentException("Transaction not found!"); } } public static void Main() { Look up the BankAccount a = new BankAccount(…); transaction Transaction t1 = a.Lookup("22N"); ... }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-10 Indexer Format

 The general format for an indexer is that of a property • Uses the keyword this with an index type • Can be overloaded visibility type this[index_type index] { visibility get { … logic … return field[index]; } visibility set { … logic … field[index] = value; } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-11 Indexer Example

public class BankAccount { private Transaction[] transactions = ... … other fields and methods … public Transaction this[string code] Index by { get transaction code { foreach (Transaction trx in transactions) { if (trx.Code == code) return trx; } throw new ArgumentException("Transaction not found!"); } } public static void Main() } { BankAccount acct; acct = new BankAccount(…); Use the indexer Transaction t1 = acct["22N"]; ... }  The syntax of an indexer might seem a little odd at first, but it is very convenient for many uses • The string type uses an indexer to allow access to individual chars

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-12 Implementing an Indexer Do Now

 To obtain a specific playing card out of a TehiGame object, the extension method .ElementAt(…) is being called • An indexer would make this more convenient 1. Launch Visual Studio and open the Tehi solution found in C:\Course\419\Do Now Demo\Do91-web or -desktop 2. Open TehiGame.cs for editing and, after the constructor, add this logic public PlayingCard this[int ix] { get { return hand[ix]; } }

3. Open Form1.cs/Default.aspx.cs for editing 4. Replace the calls to .ElementAt(…) with calls to the indexer as in game.ElementAt(2) becomes game[2]

5. Compile and test—log in and confirm your cards still display and are swappable

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-13 Chapter Contents

• Initializers

• Symbolic Operators and Indexers  Events and Delegates

• Lambda Expressions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-14 Using Delegates

 In Windows Forms and Web Forms, we saw that a delegate was used to register event methods  Delegates allow us to determine dynamically, at run time, which method should be called • A delegate specifies a reference to a method ◦ For example, provides a reference to a method rather than data  Recall the registering of a button’s Click event button1.Click += new EventHandler(button1_Click); • When the button is clicked, flow will go to the method button1_Click  EventHandler is a reference type defined using the delegate keyword delegate void EventHandler(object sender, EventArgs e); • Can represent any method as long as that method takes the same numbers and types of parameters and returns the same type

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-15 Exposing Events

 Somewhere within the button class, the delegate is exposed using the event keyword as shown in this facsimile

public class Button : Control { public event EventHandler Click; private void DoClick() // Call by CLI when button is clicked { if (Click == null) return; // Any events registered? Click(this, EventArgs.Empty); // Call method specified. } }

 Just like the Button class, we can define our own delegates and events • Very useful for tying together classes that are not otherwise known when they are being developed

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-16 Chapter Contents

• Initializers

• Symbolic Operators and Indexers

• Events and Delegates  Lambda Expressions

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-17 Using Lambda Expressions Do Now

 Improve the user interface by sorting the hand by the rank of the cards • Puts all of the eyes at one end • First, let’s find out what overloads List.Sort(…) supports

1. Launch Visual Studio and open the Tehi solution found in C:\Course\419\Do Now Demo\Do92-web or desktop 2. In TehiGame.cs, move to the Deal() method, and after the end of the loop that deals the cards, enter hand.Sort( 3. As you type the left parenthesis in hand.Sort, use IntelliSense to determine what the overloads are What are the different overloads?

4. Leave the solution open for now

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-18 The Need for Lambda Expressions

 Since List.Sort(…) accepts a CompareTo(…) method, we could write one and pass it in • CompareTo() returns a positive integer if the first is greater, a negative integer if the second is greater; otherwise, 0 public class TehiGame { ... private int ByRank(PlayingCard c1, PlayingCard c2) { return c1.Rank – c2.Rank; // Return plus, minus or 0 } private void Sort() { hand.Sort(ByRank); } }

 Wouldn’t it be nice if we could just pass in the expression? • After all, the function will only be called from one place

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-19 Lambda Expressions λ  A lambda expression is just shorthand for a method • Uses => operator to indicate the input parameters “go to” the expression  For example, the lambda expression for the following function would be:

(price) => price * .85

double Discount(double price) { return price * .85; }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-20 Writing Lambda Expressions

 Lambda expressions always look more complex than they are • When reading, it is simpler if you just ignore the left side  Type declarations are not needed since they are specified in the delegate  Can have multiple parameters What is the lambda expression equivalent of ByRank(…)?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-21 Using Lambda Expressions Do Now

 Improve the user interface by sorting the hand by the rank of the cards 1. Return to Do92 and go back to the call hand.Sort(…) method in TehiGame

2. Pass in your lambda expression the call to hand.Sort(...);

3. Compile and test • The cards displayed should now be sorted by rank 4. Close Visual Studio

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-22 Chapter Contents

• Initializers

• Symbolic Operators and Indexers

• Events and Delegates

• Lambda Expressions  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-23 Review Questions

What is the delegate specification for a standard event handler?

Where is the event keyword used?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-24 Chapter Summary

In this chapter, we have  Examined some useful C# syntax that is less commonly used • Symbolic operator overloading • Indexers • Initializers  Leveraged language features that integrate C# and the CLI runtime • Delegates • Events • Lambda expressions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-25

Chapter 10

Course Summary Course Summary

 In this course, we have discussed the syntax and semantics of C# as • An object-oriented language ◦ Using encapsulation, inheritance, interfaces, realization, polymorphism, associations, and aggregates • A component-oriented language focusing on reuse via the .NET Framework Library, including ◦ Desktop graphical and web-based user interfaces ◦ Enabling cross-language operation ◦ Performing I/O using serial streams and serialization ◦ Interfacing to legacy COM components • A data-oriented language ◦ Using LINQ and the Entity Framework

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 10-2 Where to Next?

 Learning Tree offers a comprehensive curriculum for .NET • This includes a C# certification program

Introductory programming course Programming With .NET Course 502

.NET languages

Programming C# C# Programming Visual Basic Extended Features Course 419 Programming for .NET Course 973 Course 503

.NET technologies

Programming Building Web WCF, Web API, and .NET Best Developing Apps for SharePoint 2010 Applications With SignalR Services for Practices and SharePoint 2013 Applications With .NET ASP.NET MVC .NET Design Patterns Course 2616 Course 2615 Course 977 Course 2601 Course 511

 Of particular interest for C# developers is Course 973, Programming C# Extended Features • This is a continuation C# course with advanced material, including comprehensive coverage of LINQ and the Entity Framework

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 10-3 Lagniappe

ALL THESE WORLDS ARE YOURS EXCEPT EUROPA ATTEMPT NO LANDING THERE USE THEM TOGETHER USE THEM IN PEACE

HAL-9000 Computer 2010: The Year We Make Contact

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 10-4 Appendix A

Performance Tips Objectives

We will examine various performance aspects of C#  General tips  Memory management and garbage collection  Finalization  Disposable objects  Other performance techniques

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-2 Contents

 General Tips

• Memory Management

• Weak References

• Other Techniques

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-3 What Is Performance?

 Performance is a “loaded” word • Means different things to different people ◦ User responsiveness ◦ Scalability ◦ Lots of users ◦ Throughput ◦ Time to complete  One thing is for sure—we always want faster! • Let’s discuss a few things that might help But …  Don’t obsess about it—usually getting it written takes precedence • There is no point in spending two weeks optimizing some program that only gets run once per month ◦ Especially if it only changes the runtime from 15 minutes to 12

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-4 String Performance

 Some performance improvements are as simple as picking the right class  For example, strings in C# are immutable, so how much garbage collector work must be done on the following? public static void Main() { string x = "Hello"; x = x.Append(" world"); x = x.Replace("H","J"); … more code … }

 StringBuilders are changed in place and are much faster • But are somewhat more complicated (must manage capacity) using System.Text; public static void Main() { StringBuilder x = new StringBuilder("Hello"); x.Append(" world"); x[0] = 'J'; … more code … }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-5 String Performance

 String comparison • Use Compare for case-insensitive comparisons Copies s1 to a temporary that needs garbage collection later

if (s1.Trim().ToLower() == "abc") … if (string.Compare(s1,"abc", true) == 0)…

No copy, no extra garbage

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-6 Use static or const

 static allocation can be used to avoid garbage collection

public override string ToString() These would be { created every call if (!faceUp) return "XX"; string suits = "HDCS"; string ranks = " A23456789TJQK"; These would be return "" + ranks[rank] + suits[suit]; created only once per program } private const string suits = "HDCS"; private const string ranks = " A23456789TJQK"; public override string ToString() { if (!faceUp) return "XX"; return "" + ranks[rank] + suits[suit]; }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-7 Array and Collection Performance

 Arrays and collections • Prefer arrays unless the extra functionality of a collection class is required ◦ A best practice if the size of the collection is known in advance – Like a card deck  Use non-generic collection classes • Generics are convenient (no casting), but cause as much as 20 percent overhead  Pick the right collection class • Analyze requirements before choosing the collection type  Initialize collections to the right (or slightly larger) size • If the upper limit is known

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-8 Keep Arrays Clean

 Make logically unused array elements physically unused • The compiler cannot tell, so set the unused element to null  For example, if an array was used to hold playing cards in a card deck:

public PlayingCard Deal() { PlayingCard card = deck[--cardCount]; card.IsFaceUp = false; deck[cardCount] = null; return card; This element can now be } garbage-collected if it goes out of scope somewhere else

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-9 Exception Performance

 Exceptions should be truly exceptional • Don’t use exceptions as part of the normal conditional flow of an application ◦ Do not use an exception when a standard if statement will work  Use finally blocks to guarantee release of resources

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-10 Improve Performance by Using Threads

 Sometimes performance improvement requires using threading and concurrency • async, await, and lock keywords • Task class and Action delegate  As discussed in Appendix C

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-11 Contents

• General Tips  Memory Management

• Weak References

• Other Techniques

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-12 Garbage Collector

 The garbage collector adds overhead, so we do not want it to execute any more than necessary • Runs in a separate thread  Looks for objects that no longer have references and removes them But …  Is much more than simply “counting references”; it is a “generation- oriented lazy mark and sweep mover/cleaner” • Generation-oriented: Organizes memory by the age of the allocation • Lazy: Only done when memory is needed • Marks the roots and sweeps the orphaned groups • Mover: Might move still-referenced objects • Cleaner: Calls each object at its finalize method when collected

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-13 Manually Manage the Garbage Collector

 There are few topics more controversial in .NET than the manual management of the garbage collector In most cases, this simply should not be done • If you think you need to, you are probably wrong! Notwithstanding …  The garbage collector is managed by a heuristic algorithm that by definition cannot be “perfect”  Manual assistance might produce some performance improvement in the rarest circumstances, such as • When a program enters a rarely used section of code after the extensive, prolonged, and repetitive execution of other logic • When a program switches essentially all of its operational data after the extensive, prolonged, and repetitive accessing of a different set of data

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-14 Managing the Garbage Collector

 In general, IL optimizations make it unnecessary to set references to null to have targeted objects collected • Knows when a reference is no longer used  System.GC.Collect()—will do garbage collection now

This is a flimsy example to show the syntax only • It is not a recommendation; in fact, it might slow the program down!

public class SomeForm { public static void Main() { BigThing bt = new BigThing(); bt.DoInitializationWork(); SomeForm form1 = new SomeForm(); Poor practice—why? // Initialization completed bt = null; System.GC.Collect(); GC: We will be waiting for user input Application.Run(form1); next, so now would be a good time to } do garbage collection! }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-15 Finalizers (Destructors)

 Finalize() is one of the methods in object that can be overridden  A finalizer is used to release resources when an object is going away (being removed from memory)  Called when the object is garbage-collected or on program exit • Hence, it is usually best to put cleanup code directly in the main logic • Typically, finalizers are used only as a “safety net” Note that C++ destructor-style syntax is used to override Finalize()

public class BankAccount { … other stuff … ~BankAccount() // Override object's Finalize() method { … do clean up stuff … } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-16 Suppressing Finalize

 Alternatively, finalization can be suppressed  Just before memory is recovered, the garbage collector dispatches to the occupying object’s Finalize method • A waste of time if it has not been overridden  System.GC.SuppressFinalize(object) avoids this • Removes objects from the finalizer call list ◦ Finalize will not be called

Doing this can have unpredictable results when mixed with inheritance • It is not recommended except in the context of the dispose pattern

public class Speedy { Indicate that this public Speedy() { class never needs … other constructor code … finalization System.GC.SuppressFinalize(this); } … other methods and fields … }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-17 Dispose Pattern

 The garbage collector is nondeterministic • So depending on Finalize, would also be nondeterministic  Also, the garbage collector does not recover unmanaged resources • Such as open files, streams, network channels, etc.  Enter the dispose pattern • A deterministic convention for recovering unmanaged resources • Used throughout the .NET Framework • Have seen this with Windows.Forms for closing a dialog box, for example  Implementing IDisposable in a class announces that it participates in the disposition scheme • More than just implementing the Dispose() method • Must propagate through both the containment and inheritance hierarchies

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-18 Dispose Pattern Implementation Convention

public class DThing : IDisposable { private SomeUnmgdResource handle; private SomeComponent component = new SomeComponent(); private bool disposed = false; public DThing(SomeUnmgdResource handle) { this.handle = handle; } public void Dispose() { Dispose(true); Recover everything since GC.SuppressFinalize(this); GC is not yet running } private void Dispose(bool disposing) { No longer need to be finalized if (!disposed) { Do not dispose managed Only do once if (disposing) component.Dispose(); resources; GC is doing it if (handle != null) { handle.Close(); handle = null; } disposed = true; } } ~Thing() { Dispose(false); } } If we get here, then managed resources are being collected

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-19 using Disposition Blocks

 Client code should call the Dispose() method (in a try … finally) or better yet, enclose a disposable object in a using clause • Dispose() will be called automatically—no matter what

using (DThing dthing = new DThing()) { … use dthing just like any other object … }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-20 Contents

• General Tips

• Memory Management  Weak References

• Other Techniques

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-21 The Need for Weak References

 Usually, references are strong • GC cannot recover if there is an active reference still in scope ◦ And it will still be used so the JIT cannot optimize recovery  In 32 bits, there are only 2.14 G of memory available • Part of this is probably virtual—how much real memory is on your PC?  When processing large, complicated data like video clips or images, memory can become exhausted quickly • Before running out, performance will be degraded due to use of swap file • GC will attempt to optimize swapping, but given enough memory demand, there is little it can do

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-22 Weak References

 Alternatively, weak references can be used • GC can recover still used weak-referenced memory, but… • Program logic must check if target has been recovered  Has the effect of intelligent, GC-managed memory caching  Because there is usually a delay between when an object becomes eligible for collection and when collection actually occurs • A weak reference will be automatically resurrected during this interval if it gets actively accessed again

WeakReference wr = new WeakReference(new BigThing(…)); . … other code … . if (wr.IsAlive) bt = (BigThing) wr.Target; else bt = new BigThing(…);

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-23 Using Weak References

 Example: Paging in the MagnaLearn System™ could use something like

public class Chapter { private List pageList = new List(); private int chapNo; private int maxPages; public Chapter(int chapNo, int pages) { System.GC.Collect(); this.chapNo = chapNo; maxPages = pages; for (int i = 0; i < pages; i++) pageList.Add(new WeakReference(new PageImage(chapNo,i))); } public void DisplayPage(int pageNo) { PageImage pimg = LoadPage(pageNo); pimg.Render(); if (pageNo < maxPages-1) LoadPage(pageNo+1); } private PageImage LoadPage(int pageNo) { if (!pageList[pageNo].IsAlive) { PageImage pimg = new PageImage(chapNo, pageNo); pageList[pageNo] = new WeakReference(pimg); } return (PageImage) pageList[pageNo].Target; } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-24 Contents

• General Tips

• Memory Management

• Weak References  Other Techniques

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-25 Unsafe Code

 Some performance benefits can be achieved using unsafe code blocks  Memory can be allocated on the stack (stackalloc) • Similar to using new • Fast (instant) recovery ◦ No garbage collector involvement  Requires the use of pointers • Very similar to C++

 See Appendix B for more information

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-26 Interfacing to C++

 Standard C++ uses manual memory management • delete keyword used ◦ No garbage collector  This means using it can be faster But …  It also makes it more difficult to program • Prone to memory leaks as code becomes more complex  C# can interface to C++/CLI (has a garbage collector)  Interfacing overhead can offset the gains from manual memory management

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-27 Contents

• General Tips

• Memory Management

• Weak References

• Other Techniques  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-28 Review Questions

Why should finalization not be suppressed without using the Dispose pattern?

How can client code ensure deterministic resource recovery for classes that are IDisposable?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-29 Summary

We have examined various performance aspects of C#  General tips  Memory management and garbage collection  Finalization  Disposable objects  Other performance techniques

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-30 Appendix B

Unsafe Features Objectives

We will discuss features of C# that are considered “unsafe,” including  Pointers and how they are used and manipulated  Fixed memory allocation and object pinning  stackalloc key word to allocate objects on the stack

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-2 Contents

 What Is Unsafe?

• Pointers

• Pointer Manipulation

• Pinning

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-3 What Is Unsafe?

 Languages such as Pascal, C, and C++ implement pointers • A pointer is essentially a C# reference that can be manipulated ◦ For example, used to step through memory • From an assembly language feature called indirect addressing  In C++, pointers are essentially the only mechanism to • Associate and aggregate classes • Dynamically allocate memory on the heap (new)  Pointer use was often problematic—meaning unsafe • Dangled pointer—Manipulated out of bounds of legally referenced data • Memory leak—Pointer to dynamic heap memory lost

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-4 What Is Unsafe?

 According to industry experts, these two problems account for more than 50 percent of the bugs found in a typical C++ program • Cannot be caught by the compiler at compile time • Often, they don’t appear during initial testing ◦ Lay latent until a catastrophic failure happens much later – Often exhibit misleading symptoms • Runtime tracking tools abound to help find these sorts of errors

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-5 C# Unsafe Code

 C# allows the developer to use “unsafe” practices • Pointers are supported with some limitations But …  Any block of code that uses these features must be declared unsafe  Serves two purposes • Reminds the programmer to be careful • Alerts the C# compiler to warn about this code if used directly in a publicly exposed part of a .NET component

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-6 C# Unsafe Code: Why?

Why would a developer want to use “unsafe” code? • C# seems complete without these features ◦ Java doesn’t have them  Some algorithms are more efficient when programmed with a pointer • For certain time-critical sections, unsafe use of pointers might be just the right performance solution  Pointers might also have to be used for backward compatibility • With C/C++ programs • Legacy COM applications  Pointers are useful in specialty areas such as device drivers • To deal with physical memory locations (device registers)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-7 Contents

• What Is Unsafe?  Pointers

• Pointer Manipulation

• Pinning

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-8 Pointers

 A pointer is conceptually similar to a reference, but it can be “manipulated” • A variable that contains the memory location of some object • Indirect through a pointer to examine or change the pointed-to object  Suppose • i is an int variable containing the value 453 • pi is a pointer containing the address of i  Pictorially:

i 453 pi

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-9 Pointer Data Types

 Every pointer has a type that specifies the type of object it points to • The variable p must have type pointer-to-int  In general, if a pointer points to an object of type T, its type is pointer-to-T • Pointer-to-char, pointer-to-float, pointer-to-double, etc.  There are no “just plain pointers”!

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-10 The Address Operator: &

 The “address-of” operator, &, is a unary operator • Applied to an object, it yields the address of the object  In main, suppose • i is an int variable • pi is a pointer-to-int variable

For the moment, we will ignore how pi is defined

 i and pi occupy space in memory i pi  The statements i = 200; pi = &i;

store the value 200 in i and the address of i in pi

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-11 The Indirection Operator: *

 The indirection operator, *, is also a unary operator • Applied to a pointer, it yields the object pointed to • Sometimes called (incorrectly) the dereference operator  Following the above statements, the expression *pi • Has value 200 • Has type int System.Console.WriteLine(*pi); // prints 200  In general, if P has type pointer-to-T, then *P has type T

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-12 Defining Pointer Variables

 The definition of a pointer variable uses the * symbol to provide a “hint” for using the variable • This syntax is known as “definition mimics use” MEMORY using System; public void doit() Must be declared unsafe { unsafe { char c; // c is a char char* pc; // pc is a pointer-to-char int i; // i is an int int* pi; // pi is a pointer-to-int

c = 'A'; pc = &c; pi = &i; *pi = 123; Console.WriteLine(c + " " + *pc); Console.WriteLine(i + " " + *pi); A A } 123 123  Output }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-13 Defining Pointer Variables

What if pi = &i had been omitted in the previous example?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-14 Contents

• What Is Unsafe?

• Pointers  Pointer Manipulation

• Pinning

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-15 Pointer Manipulation

 Pointers can be manipulated to step through a data structure  For example, let’s consider stepping through an array • An array in C# is allocated in memory as linear storage, so the statement:

int* pa = new int[5];

would pictorially create the following situation:

pa • • • • • •

[0] [1] [2] [3] [4]

What would happen if the next statement was *pa = 42;? What if the statement was *(pa+5) = 99;?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-16 Pointer Manipulation

 Note that adding an integer to a pointer will scale it to move along by the size of what it is pointing to

int pi

double pd

byte pb

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-17 Contents

• What Is Unsafe?

• Pointers

• Pointer Manipulation  Pinning

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-18 Pinning

 Actually, there is a problem with this statement from our previous example

int* pa = new int[5];

It won’t compile because arrays are reference types  Reference types are allocated on the heap and managed by the garbage collector (GC) So …

What would happen if the GC decided to move the object and we were pointing to it and using it?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-19 Pinning

 The garbage collector is allowed to (and needs to) move objects to defragment the heap • It doesn’t know about our access with a pointer unless we tell it  Use the fixed key word to tell the GC to pin the object • Now it won’t move or recover this object until the pointer (pa in this case) goes out of scope  For example fixed (int* pa = new int[5]) { ...code using pa... }

 We can point to any heap-allocated object as long as it is pinned • Cannot modify the pointer to heap memory ◦ But can add an integer value to it to move through the memory  Fixing can only be done on an unmanaged type

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-20 Stack Allocation

 An alternative to pinning is to allocate the referenced object(s) on the stack  Use the stackalloc key word for this purpose  For example int* pa = stackalloc int[5];

is allowed to modify pointers to stack memory  For example for (int* ip = pa; ip < (pa+5); ip++) *ip = 0;

 Note that both the pointer and the stack allocated array go out of scope at the same time • No need for a “destructor”  Stack allocation can only be done on an unmanaged type

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-21 Calling a Method

 Given a pointer to an object, to call a member function on the pointed-to object, you can write either (*pointer).member_function(args_if_any) or pointer->member_function(args_if_any)

 The * operator has lower precedence than the . operator, so you must put parentheses around *pointer  Because the parentheses are easy to forget and look ugly, the “arrow” operator -> is provided as an alternative to using * and .

unsafe { fixed (Thing* tp = new Thing()) { (*tp).do_something(); // or… tp->do_something(); } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-22 Contents

• What Is Unsafe?

• Pointers

• Pointer Manipulation

• Pinning  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-23 Review Questions

Why is unsafe code permitted in C#?

Why do we have to pin an object if we intend to have a pointer to it?

Which operator is used to call a method in an object that is referred to by a pointer?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-24 Summary

We have discussed features of C# that are considered “unsafe,” including  Pointers and how they are used and manipulated  Fixed memory allocation and object pinning  stackalloc key word to allocate objects on the stack

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. B-25

Appendix C

Other C# Features Objectives

In this appendix, we will  Examine threading, concurrency and synchronization • Asynchronous keywords

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-2 Contents

 Asynchronous Keywords

• Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-3 The Need for Asynchronous Programming Do Now

 A special version of Tehi has been written that includes the ability to test the accuracy of card deck shuffling 1. Launch Visual Studio and open the Tehi solution found in C:\Course\419\Do Now Demo\DoA1

2. In the CardLib project, open DealTester.cs and notice that it will become increasingly “compute bound” as the size of the sample increases • Note also that the correct result should be 25% 3. Run the program and select Game | Deal Test. Is the result 25%? ______• Repeat a few times to be sure 4. Open Form1.cs and move to the dealTest_Click(…) method. Change from 500 to 5000000 (5 million—add 4 zeros) 5. Run the program and test again. Does it seem to have hung? ______• Try doing something while it is running (like exit) 6. It will eventually finish—leave Visual Studio open for now

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-4 The Need for Multi-Threading

 Since the earliest days of programming, the need for asynchronous capability has been recognized • In modern times, this is called multithreading  Multithreading provides more than one path of execution through the same program • When one thread requires a resource, or must wait for an long-running operation to finish, other threads can run while it waits  .NET Framework supports pre-emptive multithreading • Not to be confused with cooperative multithreading • Memory and data is shared • Context switching is lightweight and minimal

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-5 Threading Choices

 There are multiple ways to achieve threading in C# applications: 1. Create and manage threads directly in code 2. Use asynchronous delegates 3. Use a BackgroundWorker control 4. Use the C# key words  Introduced in C# V5, the async and await key words, combined with the library Task class, significantly simplify asynchronous programming • Will likely become the primary mechanism used for multithreading

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-6 async and await Key Words

 Any method that while executing will need to wait for an asynchronous operation must be declared with the async modifier • Often, this is added to a regular event method  Once declared as async, the await key word can be used within • Applied to any expression of type IAwaitable  Logically, what we would want to do is something like

private async void dealTest_Click(object sender, EventArgs e) { DealTester tester = new DealTester(5000000); await tester.Deal(); // This will not work!!! StatusLabel.Text = "Average = " + tester.Average + "%"; }

 The above will not work because tester.Deal() is not IAwaitable

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-7 The Task Class

 It is possible to make any method in any class directly work directly with an await statement

But…  There is a much easier way using Task.Run(…) • This method is IAwaitable and can dispatch to any delegated method ◦ Directly if the delegated method has a return type ◦ Or using an Action delegate if the return type is void  For the deal tester, an Action delegate would be needed since Deal() returns void private async void dealTest_Click(object sender, EventArgs e) { DealTester tester = new DealTester(5000000); Action deal = new Action(tester.Deal); await Task.Run(deal); StatusLabel.Text = "Average = " + tester.Average + "%"; }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-8 The Need for Asynchronous Programming Do Now

 Modify Tehi to invoke the deal tester asynchronously 1. In Form1.cs, add the statement using System.Threading.Tasks; at the appropriate place 2. Add the async modifier to the declaration of dealTest_Click(…) (ignore warnings for now) 3. Replace tester.Deal() with Action deal = new Action(tester.Deal); 4. In the next line, add await Task.Run(deal);

5. Run the program and test again. Does it hang now? ______• Try playing the game while the deal tester is running 6. When it finishes, exit Visual Studio

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-9 Synchronization

 In the real world, objects that communicate asynchronously must coordinate their actions at some point  The abstract equivalent of this is synchronized access to shared data  Without proper synchronization,race conditionscan occur • Happens when two or more threads try to access some data non-atomically

public static int totalLoops = 0;

public static void CountLoops() { totalLoops = totalLoops + 1; }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-10 lock Key Word

 Fortunately, C# has a lock key word that automatically applies a mutual exclusion lock (mutex) on the object specified

private static int totalLoops = 0; private static object locker = new object(); public static void CountLoops() { lock (locker) { totalLoops = totalLoops + 1; } }

Locking must be done on a reference-type, not a value-type • Locking on total_loops, for example, would box a copy and the lock applied to the copy Be selective; any other thread that hits the lock will stall waiting for the resource to become available • If something goes wrong in the code in the lock, a deadlock can occur

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-11 The Need for Asynchronous Programming Do Now

 When threads are running, it is common to provide some feedback to the user 1. Launch Visual Studio and open the Tehi solution found in C:\Course\419\Do Now Demo\Do93-with-progress-bar

2. Open Form1.cs and move to the dealTest_Click(…) method • Notice that it now enables a progress bar and starts and stops a timer • Every time the timer ticks, the progress bar is updated 3. Run the program and test again. Does the progress bar update? • Try doing something while it is running (like exit) 4. When it finishes, exit Visual Studio

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-12 Contents

• Asynchronous Keywords  Review Questions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-13 Review Questions

What is a race condition? A deadlock?

For a method to use an await statement, what key word must be given in the methods declaration?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-14 Summary

In this appendix, we have  Examined threading, concurrency and synchronization • Asynchronous keywords

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. C-15