• No results found

20483B-ENU-TrainerHandbook

N/A
N/A
Protected

Academic year: 2021

Share "20483B-ENU-TrainerHandbook"

Copied!
560
0
0

Loading.... (view fulltext now)

Full text

(1)

O F F I C I A L M I C R O S O F T L E A R N I N G P R O D U C T

20483B

(2)

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement of Microsoft of the site or the products contained therein.

© 2012 Microsoft Corporation. All rights reserved. Microsoft and the trademarks listed at

http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the Microsoft group of companies. All other trademarks are property of their respective owners

Product Number: 20483B Part Number (if applicable): Released: xx/20xx

(3)

MICROSOFT OFFICIAL COURSE Pre-Release and Final Release Versions

These license terms are an agreement between Microsoft Corporation and you. Please read them. They apply to

the Licensed Content named above, which includes the media on which you received it, if any. These license

terms also apply to any updates, supplements, internet based services and support services for the Licensed

Content, unless other terms accompany those items. If so, those terms apply.

BY DOWNLOADING OR USING THE LICENSED CONTENT, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT

THEM, DO NOT DOWNLOAD OR USE THE LICENSED CONTENT.

If you comply with these license terms, you have the rights below.

1.

DEFINITIONS.

a. “Authorized Learning Center” means a Microsoft Learning Competency Member, Microsoft IT Academy

Program Member, or such other entity as Microsoft may designate from time to time.

b. “Authorized Training Session” means the Microsoft-authorized instructor-led training class using only

MOC Courses that are conducted by a MCT at or through an Authorized Learning Center.

c. “Classroom Device” means one (1) dedicated, secure computer that you own or control that meets or

exceeds the hardware level specified for the particular MOC Course located at your training facilities or

primary business location.

d. “End User” means an individual who is (i) duly enrolled for an Authorized Training Session or Private

Training Session, (ii) an employee of a MPN Member, or (iii) a Microsoft full-time employee.

e. “Licensed Content” means the MOC Course and any other content accompanying this agreement.

Licensed Content may include (i) Trainer Content, (ii) software, and (iii) associated media.

f. “Microsoft Certified Trainer” or “MCT” means an individual who is (i) engaged to teach a training session

to End Users on behalf of an Authorized Learning Center or MPN Member, (ii) currently certified as a

Microsoft Certified Trainer under the Microsoft Certification Program, and (iii) holds a Microsoft

Certification in the technology that is the subject of the training session.

g. “Microsoft IT Academy Member” means a current, active member of the Microsoft IT Academy

Program.

h. “Microsoft Learning Competency Member” means a Microsoft Partner Network Program Member in

good standing that currently holds the Learning Competency status.

i. “Microsoft Official Course” or “MOC Course” means the Official Microsoft Learning Product

instructor-led courseware that educates IT professionals or developers on Microsoft technologies.

(4)

k. “Personal Device” means one (1) device, workstation or other digital electronic device that you

personally own or control that meets or exceeds the hardware level specified for the particular MOC

Course.

l. “Private Training Session” means the instructor-led training classes provided by MPN Members for

corporate customers to teach a predefined learning objective. These classes are not advertised or

promoted to the general public and class attendance is restricted to individuals employed by or

contracted by the corporate customer.

m. “Trainer Content” means the trainer version of the MOC Course and additional content designated

solely for trainers to use to teach a training session using a MOC Course. Trainer Content may include

Microsoft PowerPoint presentations, instructor notes, lab setup guide, demonstration guides, beta

feedback form and trainer preparation guide for the MOC Course. To clarify, Trainer Content does not

include virtual hard disks or virtual machines.

2.

INSTALLATION AND USE RIGHTS. The Licensed Content is licensed not sold. The Licensed Content is

licensed on a one copy per user basis, such that you must acquire a license for each individual that

accesses or uses the Licensed Content.

2.1 Below are four separate sets of installation and use rights. Only one set of rights apply to you.

a. If you are a Authorized Learning Center:

i. If the Licensed Content is in digital format for each license you acquire you may either:

1. install one (1) copy of the Licensed Content in the form provided to you on a dedicated, secure

server located on your premises where the Authorized Training Session is held for access and

use by one (1) End User attending the Authorized Training Session, or by one (1) MCT teaching

the Authorized Training Session, or

2. install one (1) copy of the Licensed Content in the form provided to you on one (1) Classroom

Device for access and use by one (1) End User attending the Authorized Training Session, or by

one (1) MCT teaching the Authorized Training Session.

ii. You agree that:

1. you will acquire a license for each End User and MCT that accesses the Licensed Content,

2. each End User and MCT will be presented with a copy of this agreement and each individual

will agree that their use of the Licensed Content will be subject to these license terms prior to

their accessing the Licensed Content. Each individual will be required to denote their

acceptance of the EULA in a manner that is enforceable under local law prior to their accessing

the Licensed Content,

3. for all Authorized Training Sessions, you will only use qualified MCTs who hold the applicable

competency to teach the particular MOC Course that is the subject of the training session,

4. you will not alter or remove any copyright or other protective notices contained in the

(5)

6. you will only provide access to the Licensed Content to End Users and MCTs,

7. you will only provide access to the Trainer Content to MCTs, and

8. any Licensed Content installed for use during a training session will be done in accordance

with the applicable classroom set-up guide.

b. If you are a MPN Member.

i. If the Licensed Content is in digital format for each license you acquire you may either:

1. install one (1) copy of the Licensed Content in the form provided to you on (A) one (1)

Classroom Device, or (B) one (1) dedicated, secure server located at your premises where

the training session is held for use by one (1) of your employees attending a training session

provided by you, or by one (1) MCT that is teaching the training session, or

2. install one (1) copy of the Licensed Content in the form provided to you on one (1)

Classroom Device for use by one (1) End User attending a Private Training Session, or one (1)

MCT that is teaching the Private Training Session.

ii. You agree that:

1. you will acquire a license for each End User and MCT that accesses the Licensed Content,

2. each End User and MCT will be presented with a copy of this agreement and each individual

will agree that their use of the Licensed Content will be subject to these license terms prior

to their accessing the Licensed Content. Each individual will be required to denote their

acceptance of the EULA in a manner that is enforceable under local law prior to their

accessing the Licensed Content,

3. for all training sessions, you will only use qualified MCTs who hold the applicable

competency to teach the particular MOC Course that is the subject of the training session,

4. you will not alter or remove any copyright or other protective notices contained in the

Licensed Content,

5. you will remove and irretrievably delete all Licensed Content from all Classroom Devices and

servers at the end of each training session,

6. you will only provide access to the Licensed Content to End Users and MCTs,

7. you will only provide access to the Trainer Content to MCTs, and

8. any Licensed Content installed for use during a training session will be done in accordance

with the applicable classroom set-up guide.

c. If you are an End User:

You may use the Licensed Content solely for your personal training use. If the Licensed Content is in

digital format, for each license you acquire you may (i) install one (1) copy of the Licensed Content in

the form provided to you on one (1) Personal Device and install another copy on another Personal

Device as a backup copy, which may be used only to reinstall the Licensed Content; or (ii) print one (1)

copy of the Licensed Content. You may not install or use a copy of the Licensed Content on a device

you do not own or control.

(6)

Authorized Training Session or Private Training Session. For each license you acquire, you may

install and use one (1) copy of the Licensed Content in the form provided to you on one (1) Personal

Device and install one (1) additional copy on another Personal Device as a backup copy, which may

be used only to reinstall the Licensed Content. You may not install or use a copy of the Licensed

Content on a device you do not own or control.

ii.

Use of Instructional Components in Trainer Content. You may customize, in accordance with the

most recent version of the MCT Agreement, those portions of the Trainer Content that are logically

associated with instruction of a training session. If you elect to exercise the foregoing rights, you

agree: (a) that any of these customizations will only be used for providing a training session, (b) any

customizations will comply with the terms and conditions for Modified Training Sessions and

Supplemental Materials in the most recent version of the MCT agreement and with this agreement.

For clarity, any use of “customize” refers only to changing the order of slides and content, and/or

not using all the slides or content, it does not mean changing or modifying any slide or content.

2.2 Separation of Components. The Licensed Content components are licensed as a single unit and you

may not separate the components and install them on different devices.

2.3 Reproduction/Redistribution Licensed Content. Except as expressly provided in the applicable

installation and use rights above, you may not reproduce or distribute the Licensed Content or any portion

thereof (including any permitted modifications) to any third parties without the express written permission

of Microsoft.

2.4 Third Party Programs. The Licensed Content may contain third party programs or services. These

license terms will apply to your use of those third party programs or services, unless other terms accompany

those programs and services.

2.5 Additional Terms. Some Licensed Content may contain components with additional terms,

conditions, and licenses regarding its use. Any non-conflicting terms in those conditions and licenses also

apply to that respective component and supplements the terms described in this Agreement.

3.

PRE-RELEASE VERSIONS. If the Licensed Content is a pre-release (“beta”) version, in addition to the other

provisions in this agreement, then these terms also apply:

a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not contain the

same information and/or work the way a final version of the Licensed Content will. We may change it

for the final version. We also may not release a final version. Microsoft is under no obligation to

provide you with any further content, including the final release version of the Licensed Content.

b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, either directly or

through its third party designee, you give to Microsoft without charge, the right to use, share and

commercialize your feedback in any way and for any purpose. You also give to third parties, without

charge, any patent rights needed for their products, technologies and services to use or interface with

any specific parts of a Microsoft software, Microsoft product, or service that includes the feedback. You

will not give feedback that is subject to a license that requires Microsoft to license its software,

(7)

c. Term. If you are an Authorized Training Center, MCT or MPN, you agree to cease using all copies of the

beta version of the Licensed Content upon (i) the date which Microsoft informs you is the end date for

using the beta version,

or (ii) sixty (60) days after the commercial release of the Licensed Content,

whichever is earliest (“beta term”). Upon expiration or termination of the beta term, you will

irretrievably delete and destroy all copies of same in the possession or under your control.

4.

INTERNET-BASED SERVICES. Microsoft may provide Internet-based services with the Licensed Content,

which may change or be canceled at any time.

a. Consent for Internet-Based Services. The Licensed Content may connect to computer systems over an

Internet-based wireless network. In some cases, you will not receive a separate notice when they

connect. Using the Licensed Content operates as your consent to the transmission of standard device

information (including but not limited to technical information about your device, system and

application software, and peripherals) for internet-based services.

b. Misuse of Internet-based Services. You may not use any Internet-based service in any way that could

harm it or impair anyone else’s use of it. You may not use the service to try to gain unauthorized access

to any service, data, account or network by any means.

5.

SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some rights

to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you more

rights despite this limitation, you may use the Licensed Content only as expressly permitted in this

agreement. In doing so, you must comply with any technical limitations in the Licensed Content that only

allows you to use it in certain ways. Except as expressly permitted in this agreement, you may not:

install more copies of the Licensed Content on devices than the number of licenses you acquired;

allow more individuals to access the Licensed Content than the number of licenses you acquired;

publicly display, or make the Licensed Content available for others to access or use;

install, sell, publish, transmit, encumber, pledge, lend, copy, adapt, link to, post, rent, lease or lend,

make available or distribute the Licensed Content to any third party, except as expressly permitted

by this Agreement.

reverse engineer, decompile, remove or otherwise thwart any protections or disassemble the

Licensed Content except and only to the extent that applicable law expressly permits, despite this

limitation;

access or use any Licensed Content for which you are not providing a training session to End Users

using the Licensed Content;

access or use any Licensed Content that you have not been authorized by Microsoft to access and

use; or

transfer the Licensed Content, in whole or in part, or assign this agreement to any third party.

6.

RESERVATION OF RIGHTS AND OWNERSHIP. Microsoft reserves all rights not expressly granted to you in

this agreement. The Licensed Content is protected by copyright and other intellectual property laws and

treaties. Microsoft or its suppliers own the title, copyright, and other intellectual property rights in the

Licensed Content. You may not remove or obscure any copyright, trademark or patent notices that

appear on the Licensed Content or any components thereof, as delivered to you.

(8)

Content. These laws include restrictions on destinations, End Users and end use. For additional

information, see

www.microsoft.com/exporting

.

8.

LIMITATIONS ON SALE, RENTAL, ETC. AND CERTAIN ASSIGNMENTS. You may not sell, rent, lease, lend or

sublicense the Licensed Content or any portion thereof, or transfer or assign this agreement.

9.

SUPPORT SERVICES. Because the Licensed Content is “as is”, we may not provide support services for it.

10. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you fail

to comply with the terms and conditions of this agreement. Upon any termination of this agreement, you

agree to immediately stop all use of and to irretrievable delete and destroy all copies of the Licensed

Content in your possession or under your control.

11. LINKS TO THIRD PARTY SITES. You may link to third party sites through the use of the Licensed Content.

The third party sites are not under the control of Microsoft, and Microsoft is not responsible for the

contents of any third party sites, any links contained in third party sites, or any changes or updates to third

party sites. Microsoft is not responsible for webcasting or any other form of transmission received from

any third party sites. Microsoft is providing these links to third party sites to you only as a convenience,

and the inclusion of any link does not imply an endorsement by Microsoft of the third party site.

12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates and support services are

the entire agreement for the Licensed Content.

13. APPLICABLE LAW.

a. United States. If you acquired the Licensed Content in the United States, Washington state law governs

the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws

principles. The laws of the state where you live govern all other claims, including claims under state

consumer protection laws, unfair competition laws, and in tort.

b. Outside the United States. If you acquired the Licensed Content in any other country, the laws of that

country apply.

14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws of

your country. You may also have rights with respect to the party from whom you acquired the Licensed

Content. This agreement does not change your rights under the laws of your country if the laws of your

country do not permit it to do so.

15. DISCLAIMER OF WARRANTY. THE LICENSED CONTENT IS LICENSED "AS-IS," "WITH ALL FAULTS," AND "AS

AVAILABLE." YOU BEAR THE RISK OF USING IT. MICROSOFT CORPORATION AND ITS RESPECTIVE

AFFILIATES GIVE NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS UNDER OR IN RELATION TO

THE LICENSED CONTENT. YOU MAY HAVE ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS

WHICH THIS AGREEMENT CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS,

MICROSOFT CORPORATION AND ITS RESPECTIVE AFFILIATES EXCLUDE ANY IMPLIED WARRANTIES OR

CONDITIONS, INCLUDING THOSE OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND

NON-INFRINGEMENT.

(9)

DAMAGES UP TO USD$5.00. YOU AGREE NOT TO SEEK TO RECOVER ANY OTHER DAMAGES, INCLUDING

CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES FROM MICROSOFT

CORPORATION AND ITS RESPECTIVE SUPPLIERS.

This limitation applies to

o

anything related to the Licensed Content, services made available through the Licensed Content, or

content (including code) on third party Internet sites or third-party programs; and

o

claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence,

or other tort to the extent permitted by applicable law.

It also applies even if Microsoft knew or should have known about the possibility of the damages. The

above limitation or exclusion may not apply to you because your country may not allow the exclusion or

limitation of incidental, consequential or other damages.

Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this agreement

are provided below in French.

Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses dans ce

contrat sont fournies ci-dessous en français.

EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute

utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie

expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues

consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties

implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.

LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous

pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement

à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y

compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.

Cette limitation concerne:

• tout ce qui est relié au le contenu sous licence , aux services ou au contenu (y compris le code)

figurant sur des sites Internet tiers ou dans des programmes tiers ; et

• les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité

stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.

Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage.

Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects,

accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera

pas à votre égard.

EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus

par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays

si celles-ci ne le permettent pas.

(10)
(11)

Acknowledgments

Microsoft Learning wants to acknowledge and thank the following for their contribution toward

developing this title. Their effort at various stages in the development has ensured that you have a good classroom experience.

Lin Joyner – Content Developer

Lin Joyner is an experienced .NET Framework application developer and SQL Server expert. She has been working with the .NET Framework since it was first released and specializes in data access solutions with ADO.NET, LINQ, and the Entity Framework. Lin has been writing training courses and other instructional content for Microsoft for over 12 years.

John Sharp – Subject Matter Expert

John Sharp gained an honors degree in Computing from Imperial College, London. He has been developing software and writing training courses, guides, and books for over 25 years. John has

experience in a wide range of technologies, from database systems and UNIX through to C, C++ and C# applications for the .NET Framework, together with Java and JavaScript development. He has authored several books for Microsoft Press, including six editions of C# Step By Step, Windows Communication Foundation Step By Step, and the J# Core Reference.

Jason Lee – Subject Matter Expert

Jason Lee is a Principal Technologist with Content Master where he has been working with Microsoft products and technologies, especially SharePoint, Visual C#, and ASP.NET, for several years. Jason holds a PhD in computing and is currently MCPD and MCTS certified

Antony Norris – Subject Matter Expert

Antony Norris is a Senior Technologist with Content Master where he has been working with Microsoft products and technologies, especially Visual C# and ASP.NET MVC, for several years. Antony is an experienced developer who has contributed to many successful solutions. Antony has also authored Microsoft Learning courses on a variety of technologies, such as Windows Mobile, Windows

Communication Foundation (WCF), and Visual C#. Antony is currently MCTS certified.

Carsten Thomsen – Technical Reviewer

Carsten Thomsen is currently doing SharePoint 2010 development, but his interests are varied when it comes to IT and includes development of ASP.NET, Windows Forms, Windows Store, Windows Phone and other types of applications and components. He has authored a number of development books as well as over 20 Microsoft Learning courses.

(12)

Contents

Module 1: Review of Visual C# Syntax

Lesson 1: Overview of Writing Applications by Using Visual C# page 2 Lesson 2: Data Types, Operators, and Expressions page 8 Lesson 3: Visual C# Programming Language Constructs page 19 Lab: Developing the Class Enrollment Application page 28

Module 2: Creating Methods, Handling Exceptions, and Monitoring Applications

Lesson 1: Creating and Invoking Methods page 2 Lesson 2: Creating Overloaded Methods and Using Optional and

Output Parameters page 8

Lesson 3: Handling Exceptions page 12

Lesson 4: Monitoring Applications page 17

Lab: Extending the Class Enrollment Application Functionality page 23

Module 3: Developing the Code for a Graphical Application

Lesson 1: Implementing Structs and Enums page 2 Lesson 2: Organizing Data into Collections page 10

Lesson 3: Handling Events page 17

Lab: Writing the Code for the Grades Prototype Application page 22

Module 4: Creating Classes and Implementing Type-Safe Collections

Lesson 1: Creating Classes page 2

Lesson 2: Defining and Implementing Interfaces page 11 Lesson 3: Implementing Type-Safe Collections page 20 Lab: Adding Data Validation and Type-Safety to the Application page 31

Module 5: Creating a Class Hierarchy by Using Inheritance

Lesson 1: Creating Class Hierarchies page 2 Lesson 2: Extending .NET Framework Classes page 11 Lab: Refactoring Common Functionality into the User Class page 18

Module 6: Reading and Writing Local Data

Lesson 1: Reading and Writing Files page 2

Lesson 2: Serializing and Deserializing Data page 12 Lesson 3: Performing I/O by Using Streams page 23

Lab: Generating the Grades Report page 30

Module 7: Accessing a Database

Lesson 1: Creating and Using Entity Data Models page 2 Lesson 2: Querying Data by Using LINQ page 9

(13)

Lab: Retrieving and Modifying Grade Data page 15

Module 8: Accessing Remote Data

Lesson 1: Accessing Data Across the Web page 2 Lesson 2: Accessing Data in the Cloud page 12 Lab: Retrieving and Modifying Grade Data in the Cloud page 22

Module 9: Designing the User Interface for a Graphical Application

Lesson 1: Using XAML to Design a User Interface page 2

Lesson 2: Binding Controls to Data page 13

Lesson 3: Styling a User Interface page 20

Lab: Customizing Student Photographs and Styling the Application page 25

Module 10: Improving Application Performance and Responsiveness

Lesson 1: Implementing Multitasking page 2

Lesson 2: Performing Operations Asynchronously page 14

Lesson 3: Synchronizing Concurrent Access to Data page 24 Lab: Improving the Responsiveness and Performance of the

Application page 31

Module 11: Integrating with Unmanaged Code

Lesson 1: Creating and Using Dynamic Objects page 2 Lesson 2: Managing the Lifetime of Objects and Controlling

Unmanaged Resources page 8

Lab: Upgrading the Grades Report page 13

Module 12: Creating Reusable Types and Assemblies

Lesson 1: Examining Object Metadata page 2

Lesson 2: Creating and Using Custom Attributes page 11

Lesson 3: Generating Managed Code page 17

Lesson 4: Versioning, Signing, and Deploying Assemblies page 23 Lab: Specifying the Data to Include in the Grades Report page 31

Module 13: Encrypting and Decrypting Data

Lesson 1: Implementing Symmetric Encryption page 2 Lesson 2: Implementing Asymmetric Encryption page 10 Lab: Encrypting and Decrypting the Grades Report page 18

Lab Answer Keys

Module 1 Lab: Developing the Class Enrollment Application page 1 Module 2 Lab: Extending the Class Enrollment Application page 1 Module 3 Lab: Writing the Code for the Grades Prototype

(14)

Module 4 Lab: Adding Data Validation and Type-Safety to the

Application page 1

Module 5 Lab: Refactoring Common Functionality into the User

Class page 1

Module 6 Lab: Generating the Grades Report page 1 Module 7 Lab: Retrieving and Modifying Grade Data page 1 Module 8 Lab: Retrieving and Modifying Grade Data in the Cloud page 1 Module 9 Lab: Customizing Student Photographs and Styling

the Application page 1

Module 10 Lab: Improving the Responsiveness and Performance of

the Application page 1

Module 11 Lab: Upgrading the Grades Report page 1 Module 12 Lab: Specifying the Data to Include in the Grades Report page 1 Module 13 Lab: Encrypting and Decrypting the Grades Report page 1

(15)

About This Course

This section provides a brief description of the course, audience, suggested prerequisites, and course objectives.

Course Description

This training course teaches developers the programming skills that are required for developers to create Windows applications using the Visual C# language. During their five days in the classroom students review the basics of Visual C# program structure, language syntax, and implementation details, and then consolidate their knowledge throughout the week as they build an application that incorporates several features of the .NET Framework 4.5.

Audience

This course is intended for experienced developers who already have programming experience in C, C++, JavaScript, Objective-C, Microsoft Visual Basic®, or Java and understand the concepts of object-oriented programming.

The developers targeted by this training are professional developers who have 3-6 months of experience creating software applications for a production environment and who have a basic understanding of Windows client application development. Students should have a minimum of the following experience:

• 3 months of experience creating .NET Framework applications. • 1 month of experience using Visual Studio 2010 or Visual Studio 2012.

This course is not designed for students who are new to programming; it is targeted at professional developers with at least one month of experience programming in an object-oriented environment.

Student Prerequisites

Before attending this course, students must have at least three months professional development experience.

Additionally, developers attending this course should already have gained some limited experience using Visual C# to complete basic programming tasks. More specifically, students should have hands-on experience using Visual C# that demonstrates their understanding of the following:

• How to name, declare, initialize and assign values to variables within an application. • How to use:

o Arithmetic operators to perform arithmetic calculations involving one or more variables. o Relational operators to test the relationship between two variables or expressions. o Logical operators to combine expressions that contain relational operators.

• How to create the code syntax for simple programming statements using Visual C# language keywords and recognize syntax errors by using the Visual Studio IDE.

• How to create a simple branching structure using an if statement.

• How to create a simple looping structure using a for statement to iterate through a data array. • How to use the Visual Studio IDE to locate simple logic errors.

(16)

• How to design and build a simple user interface by using standard controls from the Visual Studio toolbox.

• How to connect to a SQL Server database and the basics of how to retrieve and store data. • How to sort data in a loop.

• How to recognize the classes and methods used in a program.

Course Objectives

After completing this course, students will be able to: • Describe the core syntax and features of Visual C#.

• Create methods, handle exceptions, and describe the monitoring requirements of large-scale applications.

• Implement the basic structure and essential elements of a typical desktop application. • Create classes, define and implement interfaces, and create and use generic collections. • Use inheritance to create a class hierarchy and to extend a .NET Framework class.

• Read and write data by using file input/output and streams, and serialize and deserialize data in different formats.

• Create and use an entity data model for accessing a database and use LINQ to query data. • Access and query remote data by using the types in the System.Net namespace and WCF Data

Services.

• Build a graphical user interface by using XAML.

• Improve the throughput and response time of applications by using tasks and asynchronous operations.

• Integrate unmanaged libraries and dynamic components into a Visual C# application. • Examine the metadata of types by using reflection, create and use custom attributes, generate

code at runtime, and manage assembly versions.

• Encrypt and decrypt data by using symmetric and asymmetric encryption.

Course Outline

The course outline is as follows:

Module 1, “Review of Visual C# Syntax"

Module 2, “Creating Methods, Handling Exceptions, and Monitoring Applications" Module 3, “Developing the Code for a Graphical Application"

Module 4, “Creating Classes and Implementing Type-Safe Collections" Module 5, “Creating a Class Hierarchy by Using Inheritance"

Module 6, “Reading and Writing Local Data" Module 7, “Accessing a Database"

(17)

Module 9, “Designing the User Interface for a Graphical Application" Module 10, “Improving Application Performance and Responsiveness" Module 11, “Integrating with Unmanaged Code"

Module 12, “Creating Reusable Types and Assemblies" Module 13, “Encrypting and Decrypting Data"

Course Materials

The following materials are included with your kit:

• Course Handbook: a succinct classroom learning guide that provides the critical technical information in a crisp, tightly-focused format, which is essential for an effective in-class learning experience.

• Lessons: guide you through the learning objectives and provide the key points that are critical to the success of the in-class learning experience.

• Labs: provide a real-world, hands-on platform for you to apply the knowledge and skills learned in the module.

• Module Reviews and Takeaways: provide on-the-job reference material to boost knowledge and skills retention.

• Lab Answer Keys: provide step-by-step lab solution guidance.

Course Companion Content: searchable, easy-to-browse digital content with integrated premium

online resources that supplement the Course Handbook.

• Modules: include companion content, such as questions and answers, detailed demo steps and additional reading links, for each lesson. Additionally, they include Lab Review questions and answers and Module Reviews and Takeaways sections, which contain the review questions and answers, best practices, common issues and troubleshooting tips with answers, and real-world issues and scenarios with answers.

• Resources: include well-categorized additional resources that give you immediate access to the most current premium content on TechNet, MSDN®, or Microsoft® Press®.

Note: For this version of the Courseware on Prerelease Software, Companion Content is not

available. However, the Companion Content will be published when the next (B) version of this course is released, and students who have taken this course will be able to download the Companion Content at that time from the

http://www.microsoft.com/learning/companionmoc site. Please check with your instructor when the ‘B’ version of this course is scheduled to release to learn when you can access Companion Content for this course.

Student Course files: includes the Allfiles.exe, a self-extracting executable file that contains all

required files for the labs and demonstrations.

Note: For this version of the Courseware on Prerelease Software, Allfiles.exe file is not available.

However, this file will be published when the next (B) version of this course is released, and students who have taken this course will be able to download the Allfiles.exe at that time from the

(18)

• Course evaluation: at the end of the course, you will have the opportunity to complete an online evaluation to provide feedback on the course, training facility, and instructor.

• To provide additional comments or feedback on the course, send an email to

[email protected]. To inquire about the Microsoft Certification Program, send an email to [email protected].

(19)

Virtual Machine Environment

This section provides the information for setting up the classroom environment to support the business scenario of the course.

Virtual Machine Configuration

In this course, you will use Microsoft® Hyper-V™ to perform the labs.

Important: At the end of each lab, you must close the virtual machine and must not save

any changes. To close a virtual machine (VM) without saving the changes, perform the following steps:

1. On the virtual machine, on the Action menu, click Close.

2. In the Close dialog box, in the What do you want the virtual machine to do? list, click

Turn off and delete changes, and then click OK.

The following table shows the role of each virtual machine that is used in this course:

Virtual machine Role

MSL-TMG1 Gateway computer for Internet access 20483B-SEA-DEV11 Development computer used for building

applications. The demonstration and lab files are located on the E:\ drive, in folders named Mod01, Mod02, and so on up to Mod13.

Software Configuration

The following software is installed on each VM: • Microsoft Windows 8 Enterprise

• Microsoft Visual Studio 2012 Ultimate • Microsoft Office Professional Plus 2010

Course Files

The files associated with the labs in this course are located in the E:\Labfiles folder on each virtual machine.

Classroom Setup

Each classroom computer will have the same virtual machines configured in the same way.

Course Hardware Level

To ensure a satisfactory student experience, Microsoft Learning requires a minimum equipment configuration for trainer and student computers in all Microsoft Certified Partner for Learning Solutions (CPLS) classrooms in which Official Microsoft Learning Product courseware is taught.

(20)

Hardware Level 6+

• Intel Virtualization Technology (Intel VT) or AMD Virtualization (AMD-V) processor

• Dual 120 GB hard disks 7200 RM SATA or better*

• 8GB or higher

• DVD drive

• Network adapter with Internet connectivity

• Super VGA (SVGA) 17-inch monitor

• Microsoft Mouse or compatible pointing device

• Sound card with amplified speakers

*Striped

In addition, the instructor computer must be connected to a projection display device that supports SVGA 1024 x 768 pixels, 16 bit colors.

(21)

Module 1

Review of Visual C# Syntax

Contents:

Module Overview 1-1

Lesson 1: Overview of Writing Application by Using Visual C# 1-2 Lesson 2: Data Types, Operators, and Expressions 1-8 Lesson 3: Visual C# Programming Language Constructs 1-19 Lab: Developing the Class Enrollment Application 1-28

Module Review and Takeaways 1-36

Module Overview

The Microsoft® .NET Framework version 4.5 provides a comprehensive development platform that you can use to build, deploy, and manage applications and services. By using the .NET Framework, you can create visually compelling applications, enable seamless communication across technology boundaries, and provide support for a wide range of business processes.

In this module, you will learn about some of the core features provided by the .NET Framework and Microsoft Visual Studio®. You will also learn about some of the core Visual C#® constructs that enable you to start developing .NET Framework applications.

Objectives

After completing this module, you will be able to:

• Describe the architecture of .NET Framework applications and the features that Visual Studio 2012 and Visual C# provide.

• Use basic Visual C# data types, operators, and expressions. • Use standard Visual C# constructs.

(22)

Lesson 1

Overview of Writing Application by Using Visual C#

The .NET Framework 4.5 and Visual Studio provide many features that you can use when developing your applications.

In this lesson, you will learn about the features that Visual Studio 2012 and the .NET Framework 4.5 provide that enable you to create your own applications.

Lesson Objectives

After completing this lesson, you will be able to: • Describe the purpose of the .NET Framework. • Describe the key features of Visual Studio 2012.

• Describe the project templates provided in Visual Studio 2012. • Create a .NET Framework application.

• Describe XAML.

What is the .NET Framework?

The .NET Framework 4.5 provides a

comprehensive development platform that offers a fast and efficient way to build applications and services. By using Visual Studio 2012, you can use the .NET Framework 4.5 to create a wide range of solutions that operate across a broad range of computing devices.

The .NET Framework 4.5 provides three principal elements:

• The Common Language Runtime (CLR). • The .NET Framework class library. • A collection of development frameworks.

The Common Language Runtime

The .NET Framework provides an environment called the CLR. The CLR manages the execution of code and simplifies the development process by providing a robust and highly secure execution environment that includes:

• Memory management. • Transactions.

• Multithreading.

The .NET Framework Class Library

The .NET Framework provides a library of reusable classes that you can use to build applications. The classes provide a foundation of common functionality and constructs that help to simplify application development by, in part, eliminating the need to constantly reinvent logic. For example, the

(23)

system. In addition to using the classes in the .NET Framework class library, you can extend these classes by creating your own libraries of classes.

Development Frameworks

The .NET Framework provides several development frameworks that you can use to build common application types, including:

• Desktop client applications, by using Windows Presentation Foundation (WPF). • Windows 8 desktop applications, by using XAML.

• Server-side web applications, by using Active Server Pages (ASP.NET) Web Forms or ASP.NET MVC. • Service-oriented web applications, by using Windows Communication Foundation (WCF).

• Long-running applications, by using Windows services.

Each framework provides the necessary components and infrastructure to get you started.

Additional Reading: For more information about the .NET Framework, see the Overview

of the .NET Framework page at http://go.microsoft.com/fwlink/?LinkID=267639.

Key Features of Visual Studio 2012

Visual Studio 2012 provides a single development environment that enables you to rapidly design, implement, build, test, and deploy various types of applications and components by using a range of programming languages.

Some of the key features of Visual Studio 2012 are: • Intuitive integrated development environment (IDE). The Visual Studio 2012 IDE provides all of the features and tools that are necessary to design, implement, build, test, and deploy applications and components.

• Rapid application development. Visual Studio 2012 provides design views for graphical components that enable you to easily build complex user interfaces. Alternatively, you can use the Code Editor views, which provide more control but are not as easy to use. Visual Studio 2012 also provides wizards that help speed up the development of particular components.

• Server and data access. Visual Studio 2012 provides the Server Explorer, which enables you to log on to servers and explore their databases and system services. It also provides a familiar way to create, access, and modify databases that your application uses by using the new table designer.

• Internet Information Services (IIS) Express. Visual Studio 2012 provides a lightweight version of IIS as the default web server for debugging your web applications.

• Debugging features. Visual Studio 2012 provides a debugger that enables you to step through local or remote code, pause at breakpoints, and follow execution paths.

• Error handling. Visual Studio 2012 provides the Error List window, which displays any errors, warnings, or messages that are produced as you edit and build your code.

(24)

• Help and documentation. Visual Studio 2012 provides help and guidance through Microsoft IntelliSense®, code snippets, and the integrated help system, which contains documentation and samples.

Additional Reading: For more information about what is new in Visual Studio 2012, see the What's New in Visual Studio 2012 page at http://go.microsoft.com/fwlink/?LinkID=267768.

Templates in Visual Studio 2012

Visual Studio 2012 supports the development of different types of applications such as Windows-based client applications, web-Windows-based applications, services, and libraries. To help you get started, Visual Studio 2012 provides application templates that provide a structure for the different types of applications. These templates:

• Provide starter code that you can build on to quickly create functioning applications. • Include supporting components and controls

that are relevant to the project type.

• Configure the Visual Studio 2012 IDE to the type of application that you are developing. • Add references to any initial assemblies that this type of application usually requires.

Types of Templates

The following table describes some of the common application templates that you might use when you develop .NET Framework applications by using Visual Studio 2012.

Template Description

Console Application Provides the environment settings, tools, project references, and starter code to develop an application that runs in a command-line interface. This type of application is considered lightweight because there is no graphical user interface.

Windows Forms

Application Provides the environment settings, tools, project references, and starter code to build a graphical Windows Forms application. WPF Application Provides the environment settings, tools, project references, and starter code to build a rich graphical Windows application. A WPF application enables you to create the next generation of Windows applications, with much more control over user interface design.

Windows Store Provides the environment settings, tools, project references, and starter code to build a rich graphical application targeted at the Windows 8 operating system. Windows Store applications enable you to reuse skills obtained from WPF development by using XAML and Visual C#, but also from web

development by using HTML 5, CSS 3.0, and JavaScript.

Class Library Provides the environment settings, tools, and starter code to build a .dll assembly. You can use this type of file to store functionality that you might want to invoke from many other applications.

(25)

Template Description

ASP.NET Web Application Provides the environment settings, tools, project references, and starter code to create a server-side, compiled ASP.NET web application.

ASP.NET MVC 4

Application Provides the environment settings, tools, project references, and starter code to create a Model-View-Controller (MVC) Web application. An ASP.NET MVC web application differs from the standard ASP.NET web application in that the application architecture helps you separate the presentation layer, business logic layer, and data access layer.

WCF Service Application Provides the environment settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.

Creating a .NET Framework Application

The application templates provided in Visual Studio 2012 enable you to start creating an application with minimal effort. You can then add your code and customize the project to meet your own requirements.

The following steps describe how to create a console application:

1. Open Visual Studio 2012.

2. In Visual Studio, on the File menu, point to

New, and then click Project.

3. In the New Project dialog box, do the following:

a. Expand Templates, Visual C#, and then click Windows. b. Click the Console Application template.

c. In the Name box, specify a name for the project.

d. In the Location box, specify the path where you want to save the project. 4. Click OK.

5. The Code Editor window now shows the default Program class, which contains the entry point method for the application.

The following code example shows the default Program class that Visual Studio provides when you use the Console Application template.

Program Class using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program {

(26)

static void Main(string[] args) {

} } }

After you create a project, you can then use the features that Visual Studio provides to create your application.

Programmer Productivity Features

Visual Studio 2012 provides a host of features that can help you to write code. When writing code, you need to recall information about many program elements. Instead of manually looking up information by searching help files or other source code, the IntelliSense feature in Visual Studio provides the information that you need directly from the editor. IntelliSense provides the following features:

• The Quick Info option displays the complete declaration for any identifier in your code. Move the mouse so that the pointer rests on an identifier to display Quick Info for that identifier, which appears in a yellow pop-up box.

• The Complete Word option enters the rest of a variable, command, or function name after you have typed enough characters to disambiguate the term. Type the first few letters of the name and then press Alt+Right Arrow or Ctrl+Spacebar to complete the word.

Overview of XAML

Extensible Application Markup Language (XAML) is an XML-based language that you can use to define your .NET application UIs. By declaring your UI in XAML as opposed to writing it in code makes your UI more portable and separates your UI from your application logic.

XAML uses elements and attributes to define controls and their properties in XML syntax. When you design a UI, you can use the toolbox and properties pane in Visual Studio to visually create the UI, you can use the XAML pane to

declaratively create the UI, you can use Microsoft

Expression Blend, or you can use other third-party tools. Using the XAML pane gives you finer grained control than dragging controls from the toolbox to the window.

The following example shows the XAML declaration for a label, textbox, and button:

Defining Controls in XAML

<Label Content="Name:" HorizontalAlignment="Left" Margin="72,43,0,0" VerticalAlignment="Top" />

<TextBox HorizontalAlignment="Left" Height="23" Margin="141,43,0,0" Text="" VerticalAlignment="Top" Width="120" />

<Button Content="Click Me!" HorizontalAlignment="Left" Margin="119,84,0,0" VerticalAlignment="Top" Width="75" />

You can use XAML syntax to produce simple UIs as shown in the previous example or to create much more complex interfaces. The markup syntax provides the functionality to bind data to controls, to use gradients and textures, to use templates for application-wide formatting, and to bind events to controls in

(27)

the window. The toolbox in Visual Studio also includes container controls that you can use to position and size your controls appropriately regardless of how your users resize their application window.

(28)

Lesson 2

Data Types, Operators, and Expressions

All applications use data. This data might be supplied by the user through a user interface, from a database, from a network service, or from some other source. To store and use data in your applications, you must familiarize yourself with how to define and use variables and how to create and use expressions with the variety of operators that Visual C# provides.

In this lesson, you will learn how to use some of the fundamental constructs in Visual C#, such as variables, type members, casting, and string manipulation.

Lesson Objectives

After completing this lesson, you will be able to: • Describe the data types provided by Visual C#. • Create and use expressions.

• Declare and assign variables. • Access type members.

• Cast data from one type to another. • Concatenate and validate strings.

What are Data Types?

A variable holds data of a specific type. When you declare a variable to store data in an application, you need to choose an appropriate data type for that data. Visual C# is a type-safe language, which means that the compiler guarantees that values stored in variables are always of the appropriate type.

Commonly Used Data Types

The following table shows the commonly used data types in Visual C#, and their characteristics.

Type Description Size (bytes) Range

int Whole numbers 4 –2,147,483,648 to 2,147,483,647 long Whole numbers (bigger range) 8 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float Floating-point numbers 4 +/–3.4 × 10^38

(29)

Type Description Size (bytes) Range double Double precision (more accurate) floating-point numbers 8 +/–1.7 × 10^308 decimal Monetary

values 16 28 significant figures char Single

character 2 N/A

bool Boolean 1 True or false

DateTime Moments in time 8 0:00:00 on 01/01/2001 to 23:59:59 on 12/31/9999 string Sequence of characters 2 per character N/A

Additional Reading: For more information about data types, see the Reference Tables

for Types (C# Reference) page at http://go.microsoft.com/fwlink/?LinkID=267770.

Expressions and Operators in Visual C#

Expressions are a central component of practically every Visual C# application, because expressions are the fundamental constructs that you use to evaluate and manipulate data. Expressions are collections of operands and operators, which you can define as follows:

• Operands are values, for example, numbers and strings. They can be constant (literal) values, variables, properties, or return values from method calls.

• Operators define operations to perform on operands, for example, addition or

multiplication. Operators exist for all of the basic mathematical operations, as well as for more advanced operations such as logical comparison or the manipulation of the bits of data that constitute a value.

All expressions are evaluated to a single value when your application runs. The type of value that an expression produces depends on the types of the operands that you use and the operators that you use. There is no limit to the length of expressions in Visual C# applications, although in practice, you are limited by the memory of your computer and your patience when typing. However, it is usually advisable

(30)

to use shorter expressions and assemble the results of expression-processing piecemeal. This makes it easier for you to see what your code is doing, as well as making it easier to debug your code.

Operators in Visual C#

Operators combine operands together into expressions. Visual C# provides a wide range of operators that you can use to perform most fundamental mathematical and logical operations. Operators fall into the following three categories:

• Unary. This type of operator operates on a single operand. For example, you can use the - operator as a unary operator. To do this, you place it immediately before a numeric operand, and it converts the value of the operand to its current value multiplied by –1.

• Binary. This type of operand operates on two values. This is the most common type of operator, for example, *, which multiplies the value of two operands.

• Ternary. There is only one ternary operator in Visual C#. This is the ? : operator that is used in conditional expressions.

The following table shows the operators that you can use in Visual C#, grouped by type.

Type Operators

Arithmetic +, -, *, /, %

Increment, decrement ++, --

Comparison ==, !=, <, >, <=, >=, is

String concatenation +

Logical/bitwise operations &, |, ^, !, ~, &&, || Indexing (counting starts from element 0) [ ]

Casting ( ), as

Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, ??

Bit shift <<, >>

Type information sizeof, typeof

Delegate concatenation and removal +, -

Overflow exception control checked, unchecked

Indirection and Address (unsafe code only) *, ->, [ ], &

Conditional (ternary operator) ?:

Expression Examples

You can combine the basic building blocks of operators and operands to make expressions as simple or as complex as you like.

(31)

+ Operator

a + 1

The + operator can operate on different data types, and the result of this expression depends on the data types of the operands. For example, if a is an integer, the result of the expression is an integer with the value 1 greater than a. If a is a double, the result is a double with the value 1 greater than a. The difference is subtle but important. In the second case (a is a double), the Visual C# compiler has to generate code to convert the constant integer value 1 into the constant double value 1 before the expression can be evaluated. The rule is that the type of the expression is the same as the type of the operands, although one or more of the operands might need to be converted to ensure that they are all compatible.

The following code example shows how to use the / operator to divide two int values.

/ Operator

5 / 2

The value of the result is the integer value 2 (not 2.5). If you convert one of the operands to a double, the Visual C# compiler will convert the other operand to a double, and the result will be a double.

The following code example shows how to use the / operator to divide a double value by an int value.

/ Operator

5.0 / 2

The value of the result now is the double value 2.5. You can continue building up expressions with additional values and operators.

The following code example shows how use the + and – operators in an expression.

+ and – Operators

a + b - 2

This expression evaluates to the sum of variables a and b with the value 2 subtracted from the result. Some operators, such as +, can be used to evaluate expressions that have a range of types.

The following code example shows how to use the + operator to concatenate two string values.

+ Operator

"ApplicationName: " + appName.ToString()

The + operator uses an operand that is a result of a method call, ToString(). The ToString() method converts the value of a variable into a string, whatever type it is.

The .NET Framework class library contains many additional methods that you can use to perform mathematical and string operations on data, such as the System.Math class.

Additional Reading: For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.

(32)

Declaring and Assigning Variables

Before you can use a variable, you must declare it so that you can specify its name and

characteristics. The name of a variable is referred to as an identifier. Visual C# has specific rules concerning the identifiers that you can use: • An identifier can only contain letters, digits,

and underscore characters.

• An identifier must start with a letter or an underscore.

• An identifier for a variable should not be one of the keywords that Visual C# reserves for its own use.

Visual C# is case sensitive. If you use the name MyData as the identifier of a variable, this is not the same as myData. You can declare two variables at the same time called MyData and myData and Visual C# will not confuse them, although this is not good coding practice.

When declaring variables you should use meaningful names for your variables, because this can make your code easier to understand. You should also adopt a naming convention and use it!

Declaring and Assigning Variable

When you declare a variable, you reserve some storage space for that variable in memory and the type of data that it will hold. You can declare multiple variables in a single declaration by using the comma separator; all variables declared in this way have the same type.

The following example shows how to declare a new variable.

Declaring a Variable

// DataType variableName; int price;

// OR

// DataType variableName1, variableName2; int price, tax;

After you declare a variable, you can assign a value to it by using an assignment statement. You can change the value in a variable as many times as you want during the running of the application. The assignment operator = assigns a value to a variable.

The following code example shows how to use the = operator to assign a value to a variable.

Assigning a Variable

// variableName = value; price = 10;

The value on the right side of the expression is assigned to the variable on the left side of the expression. You can declare a variable and assign a value to it at the same time.

The following code example declares an int named price and assigns the value 10.

Declaring and Assigning Variables

(33)

When you declare a variable, it contains a random value until you assign a value to it. This behavior was a rich source of bugs in C and C++ programs that created a variable and accidentally used it as a source of information before giving it a value. Visual C# does not allow you to use an unassigned variable. You must assign a value to a variable before you can use it; otherwise, your program might not compile.

Implicitly Typed Variables

When you declare variables, you can also use the var keyword instead of specifying an explicit data type such as int or string. When the compiler sees the var keyword, it uses the value that is assigned to the variable to determine the type.

In the following example shows how to use the var keyword to declare a variable.

Declaring a Variable by Using the var Keyword

var price = 20;

In this example, the price variable is an implicitly typed variable. However, the var keyword does not mean that you can later assign a value of a different type to price. The type of price is fixed, in much the same way as if you had explicitly declared it to be an integer variable.

Implicitly typed variables are useful when you do not know, or it is difficult to establish explicitly, the type of an expression that you want to assign to a variable.

Object Variables

When you declare an object variable, it is initially unassigned. To use an object variable, you must create an instance of the corresponding class, by using the new operator, and assign it to the object variable. The new operator does two things: it causes the CLR to allocate memory for your object, and it then invokes a constructor to initialize the fields in that object. The version of the constructor that runs depends on the parameters that you specify for the new operator.

The following code example shows how to create an instance of a class by using the new operator.

The new Operator

ServiceConfiguration config = new ServiceConfiguration();

Additional Reading: For more information about declaring and assigning variables, see the Implicitly Typed Local Variables (C# Programming Guide) page at

References

Related documents

The importance of jobs and the local tax base to citizens’ wel- fare leads directly to the second issue, namely, indirect effects transmitted through markets (or, in the

The quantities of rock excavation by ripper unit to form embankment for road formation construction shall be the net cubic content of the rock to the lines,

For new students the current masters degree requires 2 years of undergraduate work to enter, and takes 3 academic years for the acupuncture-only Masters and 4 academic years for

Spectral domain OCT used to view and quantify choroidal vascular congestion in new subretinal fluid following scleral buckling.. Robert Gizicki MD , Mohamed Haji,

Figure 44: Contour plot of horizontal instantaneous velocity for Libeccio wind simulation, at three different horizontal planes: (A) sea surface, (B) three meters under sea surface,

They agreed that the initial black student applications would be only to attend Tuskegee High School, because “everyone agreed that the Notasulga and Shorter areas [where the

The real issues here are those of the particular and the general, the methodology of Islamic thought, the lack of appreciation for the elements of time and place in the composition of

Radiation therapy (external beam) may be used for inoperable tumors, tumors that are not completely removed in surgery, atypical and malignant tumors, or recurrent tumors.. There