Sei sulla pagina 1di 763

MCT USE ONLY. STUDENT USE PROHIBITED

OFFICIAL

MICROSOFT

LEARNING

PRODUCT

MCT USE ONLY. STUDENT USE PROHIBITED OFFICIAL MICROSOFT LEARNING PRODUCT 20483A Programming in Visual C#

20483A

Programming in Visual C#

MCT USE ONLY. STUDENT USE PROHIBITED

ii Programming in Visual C#

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: 20483A

Part Number (if applicable):

Released: xx/20xx

MCT USE ONLY. STUDENT USE PROHIBITED

MICROSOFT LICENSE TERMS OFFICIAL MICROSOFT LEARNING PRODUCTS 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.

MCT USE ONLY. STUDENT USE PROHIBITED

j. “Microsoft Partner Network Member” or “MPN Member” means a silver or gold-level Microsoft Partner

Network program member in good standing.

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 Licensed Content,

MCT USE ONLY. STUDENT USE PROHIBITED

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

servers at the end of the Authorized 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.

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.

MCT USE ONLY. STUDENT USE PROHIBITED

d.

If you are a MCT.

i. For each license you acquire, you may use the Licensed Content solely to prepare and deliver an 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

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

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

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, technologies, or products to third parties because we include your feedback in them. These rights

MCT USE ONLY. STUDENT USE PROHIBITED

survive this agreement.

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.

MCT USE ONLY. STUDENT USE PROHIBITED

7. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and regulations. You

must comply with all domestic and international export laws and regulations that apply to the Licensed

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.

MCT USE ONLY. STUDENT USE PROHIBITED

16.

LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. TO THE EXTENT NOT PROHIBITED BY

LAW, YOU CAN RECOVER FROM MICROSOFT CORPORATION AND ITS SUPPLIERS ONLY DIRECT

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

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

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.

Revised December 2011

MCT USE ONLY. STUDENT USE PROHIBITED

x Programming in Visual C#

MCT USE ONLY. STUDENT USE PROHIBITED x Programming in Visual C#

MCT USE ONLY. STUDENT USE PROHIBITED

Programming in Visual C#

xi

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.

MCT USE ONLY. STUDENT USE PROHIBITED

xii Programming in Visual C#

Contents

Module 1: Review of Visual C# Syntax

Lesson 1: Overview of Writing Applications by Using Visual C#

page 3

Lesson 2: Data Types, Operators, and Expressions

page 11

Lesson 3: Visual C# Programming Language Constructs

page 25

Lab: Developing the Class Enrollment Application

page 38

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

Lesson 1: Creating and Invoking Methods

page 3

Lesson 2: Creating Overloaded Methods and Using Optional and Output Parameters

page 13

Lesson 3: Handling Exceptions

page 20

Lesson 4: Monitoring Applications

page 27

Lab: Extending the Class Enrollment Application Functionality

page 36

Module 3: Developing the Code for a Graphical Application

Lesson 1: Implementing Structs and Enums

page 3

Lesson 2: Organizing Data into Collections

page 17

Lesson 3: Handling Events

page 31

Lab: Writing the Code for the Grades Prototype Application

page 41

Module 4: Creating Classes and Implementing Type-Safe Collections

Lesson 1: Creating Classes

page 3

Lesson 2: Defining and Implementing Interfaces

page 18

Lesson 3: Implementing Type-Safe Collections

page 31

Lab: Adding Data Validation and Type-Safety to the Application

page 49

Module 5: Creating a Class Hierarchy by Using Inheritance

Lesson 1: Creating Class Hierarchies

page 3

Lesson 2: Extending .NET Framework Classes

page 17

Lab: Refactoring Common Functionality into the User Class

page 29

Module 6: Reading and Writing Local Data

Lesson 1: Reading and Writing Files

page 3

Lesson 2: Serializing and Deserializing Data

page 17

Lesson 3: Performing I/O by Using Streams

page 33

Lab: Generating the Grades Report

page 44

Module 7: Accessing a Database

Lesson 1: Creating and Using Entity Data Models

page 3

Lesson 2: Querying Data by Using LINQ

page 16

MCT USE ONLY. STUDENT USE PROHIBITED

Programming in Visual C#

xiii

Lab: Retrieving and Modifying Grade Data

page 28

Module 8: Accessing Remote Data

Lesson 1: Accessing Data Across the Web

page 3

Lesson 2: Accessing Data in the Cloud

page 19

Lab: Retrieving and Modifying Grade Data in the Cloud

page 34

Module 9: Designing the User Interface for a Graphical Application

Lesson 1: Using XAML to Design a User Interface

page 3

Lesson 2: Binding Controls to Data

page 19

Lesson 3: Styling a User Interface

page 30

Lab: Customizing Student Photographs and Styling the Application

page 39

Module 10: Improving Application Performance and Responsiveness

Lesson 1: Implementing Multitasking

page 3

Lesson 2: Performing Operations Asynchronously

page 20

Lesson 3: Synchronizing Concurrent Access to Data

page 36

Lab: Improving the Responsiveness and Performance of the Application

page 46

Module 11: Integrating with Unmanaged Code

Lesson 1: Creating and Using Dynamic Objects

page 3

Lesson 2: Managing the Lifetime of Objects and Controlling Unmanaged Resources

page 12

Lab: Upgrading the Grades Report

page 20

Module 12: Creating Reusable Types and Assemblies

Lesson 1: Examining Object Metadata

page 3

Lesson 2: Creating and Using Custom Attributes

page 16

Lesson 3: Generating Managed Code

page 26

Lesson 4: Versioning, Signing, and Deploying Assemblies

page 36

Lab: Specifying the Data to Include in the Grades Report

page 49

Module 13: Encrypting and Decrypting Data

Lesson 1: Implementing Symmetric Encryption

page 3

Lesson 2: Implementing Asymmetric Encryption

page 15

Lab: Encrypting and Decrypting the Grades Report

page 26

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 Application

page 1

MCT USE ONLY. STUDENT USE PROHIBITED

xiv Programming in Visual C#

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

MCT USE ONLY. STUDENT USE PROHIBITED

About This Course

i

About This Course

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

Course Description

Note: This first release (‘A’) MOC version of course 20483A has been developed on RTM software. Microsoft Learning will release a ‘B’ version of this course with enhanced PowerPoint slides, copy- edited content, and Course Companion content on Microsoft Learning site.

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 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

o

o

Arithmetic operators to perform arithmetic calculations involving one or more variables.

Relational operators to test the relationship between two variables or expressions.

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.

MCT USE ONLY. STUDENT USE PROHIBITED

ii About This Course

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.

How to create a method that accepts arguments and returns a value of a specified type.

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"

MCT USE ONLY. STUDENT USE PROHIBITED

About This Course

iii

Module 5, “Creating a Class Hierarchy by Using Inheritance"

Module 6, “Reading and Writing Local Data"

Module 7, “Accessing a Database"

Module 8, “Accessing Remote Data"

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.easy-to-browse digital content with integrated premium • Modules : include companion content, such as questions

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 includes the Allfiles.exe, a self-extracting executable file that contains all

MCT USE ONLY. STUDENT USE PROHIBITED

iv About This Course

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 http://www.microsoft.com/learning/companionmoc site.

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 support@mscourseware.com. To inquire about the Microsoft Certification Program, send an email to mcphelp@microsoft.com.

MCT USE ONLY. STUDENT USE PROHIBITED

About This Course

v

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:

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

following steps:

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

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

20483A-SEA-DEV11-<Module

Development computer used for building web applications. Each module uses a different copy of this virtual machine, called 20483A-SEA-DEV-01 for module 1, 20483A-SEA-DEV11-02 for module 2, and so on.

#>

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.

MCT USE ONLY. STUDENT USE PROHIBITED

vi About This Course

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.

1-1

 
 
  Module 1   Review of Visual C# Syntax Contents: 1-2 Module Overview Lesson 1: Overview
  Module 1   Review of Visual C# Syntax Contents: 1-2 Module Overview Lesson 1: Overview
  Module 1   Review of Visual C# Syntax Contents: 1-2 Module Overview Lesson 1: Overview

Module 1

 
Module 1  
  Module 1   Review of Visual C# Syntax Contents: 1-2 Module Overview Lesson 1: Overview

Review of Visual C# Syntax

Review of Visual C# Syntax
Review of Visual C# Syntax

Contents:

1-2

Module Overview Lesson 1: Overview of Writing Application by Using Visual C#

1-3

Module Overview Lesson 1: Overview of Writing Application by Using Visual C# 1-3

Lesson 2: Data Types, Operators, and Expressions

1-11

Lesson 2: Data Types, Operators, and Expressions 1-11

Lesson 3: Visual C# Programming Language Constructs

1-25

Lesson 3: Visual C# Programming Language Constructs 1-25
Lesson 3: Visual C# Programming Language Constructs 1-25
Lesson 3: Visual C# Programming Language Constructs 1-25

Lab: Developing the Class Enrollment Application Module Review and Takeaways

1-38

1-50

 
 
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  
Constructs 1-25 Lab: Developing the Class Enrollment Application Module Review and Takeaways 1-38 1-50  

1-2

Review o f Visual C# Syntax

Modu le Ove rview

1-2 Review o f Visual C# Syntax Modu le Ove rview Th ca cr an In

Th

ca

cr

an

In this module, you will learn about some of the core fe atures provid ed by the .N ET Framework

e Microsoft® .NET Frame work version 4 .5 provides a comprehens ive developm ent platform that you

n use to build , deploy, and manage app lications and services. By u sing the .NET Framework, you can

Mi

yo

O

Af

C# provide.

and

eate visually c ompelling ap plications, en able seamles s communica tion across te chnology bou ndaries,

d provide su pport for a wi de range of b usiness proce sses.

crosoft Visua l Studio®. Yo u will also lea rn about som e of the core Visual C#® c constructs tha t enable

u to start dev eloping .NET Framework a pplications.

bjectives

ter completin g this modul e, you will be able to:

Describe th e architectur e of .NET Fra mework appli cations and th e features th at Visual Stud io 2012

and Visual

Use basic V isual C# data types, operat ors, and expr essions.

Use standa rd Visual C# c onstructs.

Programming

in Visual C#

Lesso n 1

Over view o f Writi ng App licatio n by Us ing Vis ual C#

o f Writi n g Ap p licatio n by U s ing Vi s ual

The .NET Fra mework 4.5 a nd Visual Stud io provide m any features that you can applications.

In this lesson, you will learn

provide that

use when dev eloping your

about the fe atures that V isual Studio 2 012 and the . NET Framew ork 4.5

own applicati ons.

enable you to create your

Lesson O bjectives

After complet ing this lesso n, you will be able to:

Describe the purpose of the .NET Fr amework.

Describe the key featu res of Visual Studio 2012.

Describe the project te mplates prov ided in Visua l Studio 2012 .

Create a .NET Framew ork applicatio n.

1-4

Review o f Visual C# Syntax

W hat Is the

.NET Fra mework?

o f Visual C# Syntax W hat Is th e .NET Fra mework? Th e .NET

Th e .NET Frame work 4.5 pro vides a comp rehensive dev elopment pla tform that of fers a fast an d efficient

wa y to build ap plications and

to create a wide

Th e .NET Frame work 4.5 pro vides three pr incipal eleme nts:

The Comm on Language Runtime (CL R).

The .NET Fr amework cla ss library.

A collection of developm ent framewo rks.

Th e Commo n Languag e Runtime

services. By using Visual S tudio 2012, y ou can use t he .NET Fram ework 4.5

range of sol utions that o perate across a broad rang e of computi ng devices.

Th e .NET Frame work provide s an environ ment called th e CLR. The C LR manages t he execution of code an d simplifies t he developm ent process b y providing a robust and h ighly secure e xecution env ironment th at includes:

Memory m anagement.

Transaction s.

Multithread ing.

Th e .NET Fra mework Cl ass Library

Th e .NET Frame work provide s a library of reusable class es that you c an use to buil d application s. The cla sses provide a foundation of common f unctionality a nd construct s that help to simplify appl ication de velopment b y, in part, elim inating the n eed to const antly reinvent logic. For ex ample, the

Sy stem.IO.File class contain s functionality

sy stem. In addit ion to using t he classes in the .NET Fram ework class l ibrary, you ca n extend the se classes by creating you r own librarie s of classes.

D evelopmen t Framewo rks

Th e .NET Frame work provide s several dev elopment fra meworks that you can use to build com mon ap plication typ es, including:

Desktop cli ent applicatio ns, by using Windows Pres entation Fou ndation (WPF ).

that enables you to mani pulate files on

the Window s file

Programming in Visual C#

1-5

 
 

Windows 8 desktop applications, by using XAML.

• Windows 8 desktop applications, by using XAML.
• 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.

• Long-running applications, by using Windows services.

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

Each framework provides the necessary components and infrastructure to get you started.
Additional Reading: For more information about the .NET Framework, see the Overview

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

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.

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

1-6

Review o f Visual C# Syntax

K ey Featur es of Visu al Studio 2012

Visual C# Syntax K e y Featur es of Visu a l Studio 2012 a single

a single devel opment envir onment that enables you t to rapidly des ign,

Visual Studio 2012 are:

Vi sual Studio 20 12 provides

im plement, buil d, test, and d eploy various types of app lications and components by using a ra nge of pr ogramming l anguages.

So me of the ke y features of

Intuitive int egrated deve lopment envi ronment (IDE ). The Visual Studio 2012 I DE provides a ll of the features an d tools that a re necessary t o design, im plement, build d, test, and de ploy applicat ions and component s.

Rapid appli cation develo pment. Visua l Studio 2012 provides des ign views for graphical co mponents

that enable you to easily build compl ex user interfa ces. Alternati vely, you can use the Code

views, whic h provide mo re control bu t are not as e asy to use. Vi sual Studio 20 12 also provi des wizards

that help s peed up the d evelopment of particular c omponents.

Editor

Server and data access. V isual Studio 2012 provide s the Server E xplorer, whic h enables you to log on

to servers a nd explore th eir databases and system

access, and modify data bases that yo ur application uses by usin g the new tab le designer.

services. It als o provides a f amiliar way t o create,

Internet Inf ormation Ser vices (IIS) Exp ress. Visual St udio 2012 pr ovides a light weight versio n of IIS as the default web server fo r debugging your web ap plications.

Debugging features. Vis ual Studio 20 12 provides a debugger th at enables yo u to step thro ugh local or remote c ode, pause a t breakpoints , and follow e xecution pat hs.

Error handl ing. Visual St udio 2012 pro vides the Err or List windo w, which disp lays any erro rs, warnings, o r messages t hat are produ ced as you ed it and build y your code.

Help and d ocumentatio n. Visual Stud io 2012 provi des help and guidance thr ough Microso ft IntelliSense ®, code snip pets, and the integrated he lp system, w hich contains documentati on and samples.

lp system, w h ich contains documentati on and samples. Addition al Reading: F or more

Addition al Reading: F or more info rmation abou t what is new in Visual Stu dio 2012, see th e What's Ne w in Visual S tudio 2012 p age at http:// go.microsoft .com/fwlink/? LinkID=2677 68.

Programming in Visual C# 1- 7 Template s in Visua l Studio 2 012 Visual
Programming
in Visual C#
1- 7
Template s in Visua l Studio 2 012
Visual Studio 2012 support s the develop ment of diffe rent types of applications such as Wind ows-based
client applica tions, web-ba sed applicati ons, services,
and libraries. To help you g et started, Vi sual Studio
2012 provide s application templates tha t provide a st ructure for th e different ty pes of applic ations. These
templates:
• Provide s tarter code th at you can b uild on to qui ckly create fu nctioning ap plications.
• Include s upporting co mponents an d controls tha t are relevant to the proje ct type.
• Configur e the Visual S tudio 2012 ID E to the type of applicatio n that you ar e developing.
• Add refe rences to any initial assem blies that this type of appli cation usually requires.
Types of T emplates
The following table describ es some of t he common a pplication te mplates that y ou might use
develop .NET Framework a pplications b y using Visual Studio 2012.
when you
Template
Descript ion
Console Ap plication
Provide s the environ ment settings , tools, projec t references, and starter co de
to deve lop an applic ation that run s in a comma nd-line interf ace. This type
applicat ion is conside red lightweig ht because t here is no gra phical user
interfac e.
of
Windows F orms
Application
Provide s the environ ment settings , tools, projec t references, and starter co de
to build a graphical
Windows For ms application .
WPF Applic ation
Provide s the environ ment settings , tools, projec t references, and starter co de
to build a rich graphi cal Windows application. A
WPF applica tion enables you
to creat e the next ge neration of W indows appli cations, with much more
control over user inte rface design.
Windows St ore
Provide s the environ ment settings , tools, projec t references, and starter co de
to build a rich graphi cal applicatio n targeted at the Window s 8 operating
system. Windows Sto re application s enable you to reuse skill s obtained fro m
WPF de velopment by
using XAML and Visual C #, but also fro m web
develop ment by usin g HTML 5, CS S 3.0, and Jav aScript.

1-8

Review of Visual C# Syntax

 
 
   

Template

Description

Template Description
   
   

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.

You can use this type of file to store functionality that you might want to invoke
that you might want to invoke from many other applications. ASP.NET Web Application Provides the environment
that you might want to invoke from many other applications. ASP.NET Web Application Provides the environment

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.

the application architecture helps you separate the presentation layer, business logic layer, and data access layer.
layer, business logic layer, and data access layer.       WCF Service Application Provides the
 
 
   

WCF Service Application

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

settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.
 
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
settings, tools, project references, and starter code to build Service Orientated Architecture (SOA) services.  
Programming in Visual C# 1- 9 Creating a .NET Fra mework Applicatio n The applicatio
Programming
in Visual C#
1- 9
Creating
a .NET Fra mework Applicatio n
The applicatio n templates provided in V isual Studio 2 012 enable y ou to start cr eating an app lication with
minimal effor t. You can th en add your c ode and cust omize the pro ject to meet your own req uirements.
The following steps describ e how to cre ate a console application:
1. Open Vis ual Studio 20 12.
2. In Visual Studio, on th e File menu,
point to New , and then cli ck Project.
3. In the Ne w Project di alog box, do the following:
a. Expa nd Template s, Visual C#, and then clic k Windows.
b. Click the Console Application template.
c. In th e Name box, specify a nam e for the pro ject.
d. In th e Location b ox, specify th e path where you want to s save the proje ct.
4. Click OK.
5. The Cod e Editor wind ow now show s the default Program cla ss, which con tains the entr y point
method f or the applic ation.
The following code examp le shows the
default Progr am class that Visual Studio
provides wh en you use
the Console
Application t emplate.
Program Cla ss
using Syst em;
using Syst em.Collectio ns.Generic;
using Syst em.Linq;
using Syst em.Text;
using Syst em.Threading .Tasks;
namespace ConsoleAppli cation1
{
class P rogram
{
sta tic void Mai n(string[] args)
{
}
}

1-10

Review of Visual C# Syntax

 
 

}

}

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

After you create a project, you can then use the feat ures that Visual Studio provides

Programmer Productivity Features

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.

that the pointer rests on an identifier to display Quick Info for that identifier, which appears
for that identifier, which appears in a yellow pop-up box. • The Complete Word option enters
for that identifier, which appears in a yellow pop-up box. • The Complete Word option enters
for that identifier, which appears in a yellow pop-up box. • The Complete Word option enters

The Complete Word option enters the rest of a variable, command, or function name after you have

• The Complete Word option enters the rest of a variable, command, or functi on name

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.

the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or
the term. Type the first few letters of the name and then press Alt+Right Arrow or

Programming i n Visual C#

Lesso n 2

Data Types, Opera tors, a nd Exp ression s

Lesso n 2 Data Types, Opera tors, a nd Exp r ession s All applicatio n

All applicatio ns use data. T his data migh t be supplied by the user t hrough a use r interface, fr om a database, fro m a network s ervice, or fro m some othe r source. To s tore and use data in your a pplications, you must fam iliarize yours elf with how t o define and use variables and how to c reate and us e expressions with the varie ty of operato rs that Visual C# provides.

In this lesson, you will learn

type member s, casting, an d string mani pulation.

Lesson O bjectives

After complet ing this lesso n, you will be able to:

Describe the data type s provided b y Visual C#.

Create an d use expres sions.

Declare a nd assign var iables.

Access ty pe members.

Cast data from one ty pe to another .

Concaten ate and valid ate strings.

how to use some of the f undamental c onstructs in

Visual C#, suc h as variables ,

W hat are D ata Types s? A variable hold s data of a sp
W hat are D ata Types s?
A variable hold s data of a sp ecific type. W hen you decl are a variable to store data in an applica tion, you
ne ed to choose an appropria te data type for that data. Visual C# is a type-safe lan guage, whic h means
th at the compil er guarantees that values s tored in varia bles are alwa ys of the app ropriate type.
C ommonly U sed Data T ypes
Th
e following t able shows th e commonly used data typ es in Visual C #, and their c haracteristics .
T
ype
Desc ription
Size (b ytes)
Range
i
nt
Wh ole numbers
4
–2,147,48 3,648 to 2,14 7,483,647
l
ong
Wh ole numbers
(big ger range)
8
–9,223,37 2,036,854,77 5,808 to
9,223,372
,036,854,775, 807
float
Floa ting-point
4
+/–3.4 ×
10^38
num bers
double
Dou ble precision
(mo re accurate)
floa ting-point
num bers
8
+/–1.7 ×
10^308
decimal
Mo netary values
16
28 signific ant figures
char
Sing le character
2
N/A
bool
Boo lean
1
True or fa lse
DateTime
Mo ments in time
8
0:00:00 o n 01/01/2001 to
23:59:59
on 12/31/999 9
string
Seq uence of
char racters
2 per character
N/A

1-12

Review of Visual C# Syntax

Programming in Visual C#

1-13

Additional Reading: For more information about data types, see the Reference Tables for Types (C#
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.
E xpression s and Ope rators in Visual C# Ex pressions are a central com
E xpression s and Ope rators in Visual C#
Ex pressions are a central com ponent of pr actically ever y Visual C# a pplication, be cause express ions are
th e fundamenta l constructs t hat you use t o evaluate an d manipulate data. Expres sions are colle ctions of
op erands and o perators, whi ch you can d efine as follow s:
• Operands a re values, for example, nu mbers and str ings. They ca n be constant (literal) value s,
variables, p roperties, or
return values from method calls.
• Operators define operati ons to perfor m on operan ds, for examp le, addition o r multiplicati on.
Operators
exist for all of the basic ma thematical op erations, as w ell as for mo re advanced
operations
such as log ical comparis on or the ma nipulation of the bits of da ta that consti tute a value.
All expressions are evaluated to a single v alue when yo ur application
runs. The ty pe of value th at an
ex pression prod uces depend s on the type s of the opera nds that you use and the
operators tha t you use.
Th ere is no limi t to the lengt h of expressio ns in Visual C # application s, although i n practice, yo u are
lim ited by the m emory of yo ur computer and your pati ence when ty ping. Howev er, it is usually advisable
to use shorter e xpressions an d assemble t he results of e xpression-pr ocessing piec emeal. This m akes it
ea sier for you t o see what yo ur code is do ing, as well as
making it ea sier to debug your code.
O perators in Visual C#
O perators com bine operand s together int o expressions . Visual C# pr ovides a wide
range of op erators that
yo u can use to
perform most fundamenta l mathematic al and logical operations. O perators fall into the
fol lowing three categories:
• Unary. This type of oper ator operates on a single o perand. For e xample, you can use the - operator as
a unary op erator. To do this, you plac e it immediat ely before a n umeric oper and, and it co nverts the
value of th e operand to its current val ue multiplied by –1.
• Binary. This type of oper and operates on two value s. This is the most commo n type of ope rator, for
example, *, which multip lies the value of two opera nds.
• Ternary. Th ere is only on e ternary ope rator in Visua l C#. This is t he ? : operato r that is used in
conditional expressions.
Th e following t able shows th e operators t hat you can u se in Visual C #, grouped b y type.
T ype
Operators

1-14

Review of Visual C# Syntax

Programming in Visual C#

1-15

 
 
   

Type

Operators

Type Operators
   
   

Arithmetic

+, -, *, /, %

Arithmetic +, -, *, /, %

Increment, decrement

++, --

Increment, decrement ++, --
   

Comparison

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

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

String concatenation

+

String concatenation +

Logical/bitwise operations

&, |, ^, !, ~, &&, ||

Logical/bitwise operations &, |, ^, !, ~, &&, ||

Indexing (counting starts from element 0)

[ ]

|| Indexing (counting starts from element 0) [ ] Casting ( ), as Assignment =, +=,

Casting

( ), as

(counting starts from element 0) [ ] Casting ( ), as Assignment =, +=, -=, *=,
(counting starts from element 0) [ ] Casting ( ), as Assignment =, +=, -=, *=,

Assignment

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

   

Bit shift

<<, >>

Bit shift <<, >>
   

Type information

sizeof, typeof

Type information sizeof, typeof
   

Delegate concatenation and removal

+, -

Delegate concatenation and removal +, -

Overflow exception control

checked, unchecked

Overflow exception control checked, unchecked

Indirection and Address (unsafe code only)

*, ->, [ ], &

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

Conditional (ternary operator)

?:

Conditional (ternary operator) ?:

Expression Examples

 
Expression Examples  

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

can combine the basic building blocks of operators and operands to make expressions as simple or

The following code example shows how to use the + operator.

The following code example shows how to use the + operator.

+ Operator

 
+ Operator  

a + 1

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.

of the operands, although one or more of the operands might need to be converted to
to be converted to ensure that they are all compatible. The following code example shows how
to be converted to ensure that they are all compatible. The following code example shows how
to be converted to ensure that they are all compatible. The following code example shows how
to be converted to ensure that they are all compatible. The following code example shows how
to be converted to ensure that they are all compatible. The following code example shows how

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

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

/ Operator

 
/ Operator  

5 /

2

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.

1-16

Review of Visual C# Syntax

 
 

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

The following code example shows how to use the / operator to divide a double value
The following code example shows how to use the / operator to divide a double 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.

of the result now is the double value 2.5. You can continue building up expressions with
up expressions with additional values and operators. The following code example shows how use the +

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

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

+

and – Operators

+ and – Operators
+ 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.

Some operators, such as + , can be used to evaluate expressions that have a range

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

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

+

Operator

 
+ Operator  
+ 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.

methods that you can use to perform mathematical and string operations on data, such as the
methods that you can use to perform mathematical and string operations on data, such as the
 
 
 

Additional Reading: For more information about operators, see the C# Operators page at

http://go.microsoft.com/fwlink/?LinkID=267771.

For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
For more information about operators, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
Programming i n Visual C# 1-1 7 Declaring and Assi gning Var iables Before you
Programming i n Visual C#
1-1 7
Declaring and Assi gning Var iables
Before you ca n use a varia ble, you must declare it so that you can specify its na me and chara cteristics. The
name of a var iable is referr ed to as an id entifier. Visu al C# has spe cific rules con cerning the id dentifiers that
you can use:
• An identi fier can only contain letter s, digits, and underscore c haracters.
• An identi fier must star t with a letter or an unders core.
• An identi fier for a vari able should n ot be one of the keywords that Visual C # reserves for its own use.
Visual C# is c ase sensitive. If you use the name MyDa ta as the ide ntifier of a var riable, this is n ot the same
as myData. Y ou can declar e two variabl es at the sam e time called MyData and myData and Visual C#
will not confu se them, alth ough this is n ot good codi ng practice.
When declari ng variables y ou should us e meaningful names for yo ur variables, because this c can make
your code eas sier to unders tand. You sho uld also ado pt a naming c onvention an d use it!
Declaring a nd Assigni ing Variabl e
When you de clare a variab le, you reserv e some stora ge space for t hat variable i n memory an d the type of
data that it w ill hold. You c an declare m ultiple variab les in a single declaration b y using the c omma
separator; all variables dec lared in this w ay have the s ame type.
The following example sho ws how to de clare a new v ariable.
Declaring a
Variable
// DataTyp e variableNa me;
int price;
// OR
// DataTyp e variableNa me1, variab leName2;
int price, tax;
After you dec lare a variabl e, you can ass ign a value to
change the va alue in a varia ble as many t imes as you
assignment o perator = ass igns a value t o a variable.
it by using a n assignmen t statement. Y ou can
want during t he running of the applicati on. The
The following code examp le shows how to use the = operator to a ssign a value to a variable.

1-18

Review of Visual C# Syntax

 
 

Assigning a Variable

Assigning a Variable

// variableName = value; price = 10;

Assigning a Variable // variableName = value; price = 10; The value on the right side

The value on the right side of the expression is assigned to the variable on the left side of the expression.

The value on the right side of the expression is assigned to the variable on the

You can declare a variable and assign a value to it at the same time.

You can declare a variable and assign a value to it at the same time.
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

int price = 10;

int price = 10;

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.

variable. You must assign a value to a variable before you can use it; otherwise, your
you can use it; otherwise, your program might not compile. Implicitly Typed Variables When you declare
you can use it; otherwise, your program might not compile. Implicitly Typed Variables When you declare

Implicitly Typed Variables

Implicitly Typed Variables

When you declare variables, you can also use the var keyword instead of specifying an explicit data type

var keyword instead of specifying an explicit data type such as int or string . When

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

example shows how to use the var keyword to declare a variable. Declaring a Variable by
example shows how to use the var keyword to declare a variable. Declaring a Variable by

var price = 20;

var price = 20;
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.

of an expression that you want to assign to a variable. Object Variables When you declare
of an expression that you want to assign to a variable. Object Variables When you declare
of an expression that you want to assign to a variable. Object Variables When you declare

Object Variables

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.

you must create an instance of the corresponding class, by using the new operator, and assign

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.

that object. The version of the constructor that runs depends on the parameters that you specify
on the parameters that you specify for the new operator. The following code example shows how

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

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

The new Operator

The new Operator

ServiceConfiguration config = new ServiceConfiguration();

ServiceConfiguration config = new ServiceConfiguration();
Additional Reading: For more information about declaring and assigning variables, see the Implicitly Typed Local

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

about declaring and assigning variables, see the Implicitly Typed Local Variables (C# Programming Guide) page at
about declaring and assigning variables, see the Implicitly Typed Local Variables (C# Programming Guide) page at
about declaring and assigning variables, see the Implicitly Typed Local Variables (C# Programming Guide) page at

http://go.microsoft.com/fwlink/?LinkID=267772.

http://go.microsoft.com/fwlink/?LinkID=267772.
Programming i n Visual C# 1-1 9 Accessing Type Me mbers To access a m
Programming i n Visual C#
1-1 9
Accessing Type Me mbers
To access a m ember of an instance of a type, use the name of the instance, follo wed by a pe riod, followed
by the name of the memb er. This is kno wn as dot no tation. Consid er the follow ing rules and guidelines
when you acc ess a membe r of an instan ce:
• To access a method, u se parenthese s after the na me of the m ethod. In the parentheses, pass the
values fo r any parame ters that the
parenthe ses are still re quired.
method requi res. If the me thod does no t take any pa rameters, the
• To access a public pro perty, use the property na me. You can t hen get the v alue of that p roperty or
set the va lue of that p roperty.
The following code examp le shows how to invoke th e members th at the Servic eConfigurati on class
exposes.
Invoking Me mbers
var config = new Servi ceConfigura tion();
// Invoke the LoadConf iguration m ethod.
var loadSu ccessful = c onfig.LoadC onfiguratio n();
// Get the value from the Applica tionName pr operty.
var applic ationName = config.Appl icationName ;
// Set the .DatabaseSe rverName pr operty.
config.Dat abaseServerN ame = "78.4 5.81.23";
// Invoke the SaveConf iguration m ethod.
var saveSu ccessful = c onfig.SaveC onfiguratio n();
Additio nal Reading : For more in formation ab out using pro perties, see th e Properties (C#
Programmin g Guide) pag e at http://g o.microsoft.co m/fwlink/?Li nkID=267773 .
Additio nal Reading : For more in formation ab out using met hods, see the Methods (C #
Programmin g Guide) pag e at http://g o.microsoft.co m/fwlink/?Li nkID=267774 .
C asting Bet ween Da ta Types W hen you are d eveloping an application,
C asting Bet ween Da ta Types
W hen you are d eveloping an application, you will often
need to con vert data from
m one type to another
ty pe, for examp le, when a va lue of one ty pe is assigned to a variable of a different t type. Consid er the
sc enario where a user enters a number int o a text box. To use this nu mber in a nu merical calcu lation, you
wi ll need to con vert the strin g value 99 th at you have r ead from the text box into the integer v alue 99 so
th at you can sto re it in an int eger variable . The process of converting
ty pe is called ty pe conversio n or casting.
a value of o ne data type to another
Th ere are two t ypes of conve rsions in the .NET Framew ork:
• Implicit con version, whic h is automati cally perform ed by the CL R on operatio ns that are gu aranteed
to succeed without losin g information .
• Explicit con version, whic h requires yo u to write cod e to perform a conversion that otherwi se could
lose inform ation or prod uce an error.
Ex plicit convers ion reduces t he possibility of bugs in yo ur code and
makes your c ode more effi cient. Visual
C#
prohibits im plicit convers ions that lose precision. Ho wever, be aw are that som e explicit con versions
ca n yield unexp ected results.
Im plicit Con versions
An
implicit con version occur s when a valu e is converted
automatical ly from one d ata type to a nother. The
co nversion doe s not require any special sy ntax in the so urce code. V isual C# only allows safe im plicit
co nversions, su ch as the wid ening of an in teger.
Th e following c ode example shows how d ata is convert ed implicitly from an integ er to a long, which is
te rmed widenin g.
Im plicit Conve rsion
i nt a = 4;
l ong b;
b = a;
// Implici t conversio n of int to long.
Th is conversion always succe eds and neve r results in a l oss of inform ation. Howev er, you canno t implicitly
co nvert a long value to an in t, because th is conversion risks losing in formation (t he long value might be
ou tside the ran ge supported by the int ty pe). The follo wing table sh ows the impli cit type conv ersions that
ar e supported i n Visual C#.

1-20

Review of Visual C# Syntax

Programming in Visual C#

1-21

 
 
   

From

To

From To
   
   

sbyte

short, int, long, float, double, decimal

sbyte short, int, long, float, double, decimal

byte

short, ushort, int, uint, long, ulong, float, double, decimal

byte short, ushort, int, uint, long, ulong, float, double, decimal

short

int, long, float, double, decimal

short int, long, float, double, decimal

ushort

int, uint, long, ulong, float, double, decimal

ushort int, uint, long, ulong, float, double, decimal

int

long, float, double, decimal

int long, float, double, decimal

uint

long, ulong, float, double, decimal

uint long, ulong, float, double, decimal

long, ulong

float, double, decimal

long, ulong float, double, decimal
long, ulong float, double, decimal

float

double

char

ushort, int, uint, long, ulong, float, double, decimal

char ushort, int, uint, long, ulong, float, double, decimal
ushort, int, uint, long, ulong, float, double, decimal   Explicit Conversions   In Visual C#, you
 

Explicit Conversions

 
Explicit Conversions  

In Visual C#, you can use a cast operator to perform explicit conversions. A cast specifies the type to convert to, in round brackets before the variable name.

to perform explicit conversions. A cast specifies the type to convert to, in round brackets before

The following code example shows how to perform an explicit conversion.

The following code example shows how to perform an explicit conversion.

Explicit Conversion

Explicit Conversion

int a; long b = 5; a = (int) b;

 
int a; long b = 5; a = (int) b;  

// Explicit conversion of long to int.

// Explicit conversion of long to int.
 

You can also perform an explicit conversion by using the as operator, but only for reference type objects. The advantage of using the as operator is that if the conversion fails due to the types being incompatible, instead of the CLR throwing an InvalidCastException, the cast operation will return null, which you can then check for in your code.

CLR throwing an InvalidCastException , the cast operation will return null , which you can then
return null , which you can then check for in your code. The following code example

The following code example shows how to use the as operator to cast between two data types.

The following code example shows how to use the as operator to cast between two data

Conversions by Using the as Operator

 
Conversions by Using the as Operator  

int a; long b = 5; a = b as int;

if (a != null)

 
int a; long b = 5; a = b as int; if (a != null)  
int a; long b = 5; a = b as int; if (a != null)  

{

{

// Cast successful.

}

 
// Cast successful. }  
 
 

You can only perform meaningful conversions in this way, such as converting a long to an int. You cannot use a cast if the format of the data has to physically change, such as if you are converting a string to an integer. To perform these types of conversions, you can use the methods of the System.Convert class.

a string to an integer . To perform these types of conversions, you can use the
types of conversions, you can use the methods of the System.Convert class. Using the System.Convert Class

Using the System.Convert Class

 
Using the System.Convert Class  

The System.Convert class provides methods that can convert a base data type to another base data type. These methods have names such as ToDouble, ToInt32, ToString, and so on. All languages that target

1-22

Review of Visual C# Syntax

 
 

the CLR can use this class. You might find this class easier to use for conversions than implicit or explicit conversions because IntelliSense helps you to locate the conversion method that you need.

than implicit or explicit conversions because IntelliSense helps you to locate the conversion method that you

The following code example converts a string to an int.

The following code example converts a string to an int.

Conversions by Using the ToInt32 Method

Conversions by Using the ToInt32 Method

string possibleInt = "1234"; int count = Convert.ToInt32(possibleInt);

string possibleInt = "1234"; int count = Convert.ToInt32(possibleInt);

Some of the built-in data types in Visual C# also provide a TryParse method, which enables you to determine whether the conversion will succeed before you perform the conversion.

The following code example shows how to convert a string to an int by using the int.TryParse() method.

conversion. The following code example shows how to convert a string to an int by using
a string to an int by using the int.TryParse() method. TryParse Conversion int number = 0;

TryParse Conversion

TryParse Conversion

int number = 0;

int number = 0;

string numberString = "1234"; if (int.TryParse(numberString, out number))

string numberString = "1234"; if (int.TryParse(numberString, out number))

{

// Conversion succeeded, number now equals 1234.

// Conversion succeeded, number now equals 1234.

}

else

{

else {

// Conversion failed, number now equals 0.

}

// Conversion failed, number now equals 0. }
 
 
Additional Reading: For more information about casting variables, see the Casting and Type Conversions (C#

Additional Reading: For more information about casting variables, see the Casting and Type Conversions (C# Programming Guide) page at

http://go.microsoft.com/fwlink/?LinkID=267775.

see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
see the Casting and Type Conversions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkID=267775.
Programming i n Visual C# 1-2 3 Manipula ting Strin gs Strings are a very
Programming i n Visual C#
1-2 3
Manipula ting Strin gs
Strings are a
very useful da ta type that e nable you to capture and store alphanu meric data.
Concatena ting String s
Concatenatin g multiple str ings in Visual C# is simple to achieve by using the +
operator. Ho wever, this is
considered b ad coding pra ctice because
strings are i mmutable. Th is means that every time y ou
concatenate a
string, you c reate a new s tring in mem ory and the o ld string is di scarded.
The following code examp le creates five string values as it runs.
Concatenati on by Using
the + Operat or
string add ress = "23";
address = address + ", Main Stree t";
address = address + ", Buffalo";
An alternative
approach is to use the St ringBuilder c lass, which e nables you to build a string dynamically
and much mo re efficiently.
The following code examp le shows how to use the St ringBuilder class.
Concatenati on by Using
the StringBu ilder Class
StringBuil der address = new Strin gBuilder();
address.Ap pend("23");
address.Ap pend(", Main Street");
address.Ap pend(", Buff alo");
string con catenatedAdd ress = addr ess.ToStrin g();
Validating Strings
When acquiri ng input from
the user inte erface of an a pplication, da ta is often pr ovided as stri ngs that you
need to valid ate and then convert into a
format that your applicat ion logic exp ects. For exam ple, a text
box control in
a WPF appli cation will ret urn its conte nts as a string , even if a us er specified a n integer
value. It is im portant that y ou validate s uch input so t hat you mini mize the risk of errors, suc h as
InvalidCastE xceptions.
Regular expre ssions provid e a mechanis m that enabl es you to vali date input. Th e .NET Frame work
provides the
System.Text. RegularExpr essions nam espace that in cludes the R egex class. Yo u can use the

1-24

Review of Visual C# Syntax

 
 

Regex class in your applications to test a string to ensure that it conforms to the constraints of a regular expression.

class in your applications to test a string to ensure that it conforms to the constraints

The following code example shows how to use the Regex.IsMatch method to see if a string value contains any numerical digits.

Regex.IsMatch Method

how to use the Regex.IsMatch method to see if a string value contains any numerical digits.
how to use the Regex.IsMatch method to see if a string value contains any numerical digits.

var textToTest = "hell0 w0rld";

var textToTest = "hell0 w0rld";

var regularExpression = "\\d"; var result = Regex.IsMatch(textToTest, regularExpression, RegexOptions.None); if (result)

= "\\d"; var result = Regex.IsMatch(textToTest, regularExpression, RegexOptions.None); if (result)

{

{

// Text matched expression.

}

}

Regular expressions provide a selection of expressions that you can use to match to a variety of data types. For example, the \d expression will match any numeric characters.

the \d expression will match any numeric characters. Additional Reading: For more information about using
the \d expression will match any numeric characters. Additional Reading: For more information about using
Additional Reading: For more information about using regular expressions, see the Regex Class page at

Additional Reading: For more information about using regular expressions, see the Regex Class page at http://go.microsoft.com/fwlink/?LinkID=267776.

information about using regular expressions, see the Regex Class page at http://go.microsoft.com/fwlink/?LinkID=267776.
information about using regular expressions, see the Regex Class page at http://go.microsoft.com/fwlink/?LinkID=267776.
information about using regular expressions, see the Regex Class page at http://go.microsoft.com/fwlink/?LinkID=267776.
information about using regular expressions, see the Regex Class page at http://go.microsoft.com/fwlink/?LinkID=267776.