learning-object-oriented-programming-in-c-sharp-5.0.pdf

671

Upload: cristi-popa

Post on 18-Aug-2015

56 views

Category:

Documents


17 download

TRANSCRIPT

LearningObject-OrientedProgrammingin C# 5.0B. M. HarwaniCengage Learning PTRAustraliaBrazil JapanKoreaMexicoSingaporeSpainUnitedKingdomUnitedStatesLearning Object-OrientedProgramming in C# 5.0B. M. HarwaniPublisher and General Manager,Cengage Learning PTR: Stacy L. HiquetAssociate Director of Marketing:Sarah PanellaManager of Editorial Services:Heather TalbotSenior Marketing Manager:Mark HughesProduct Manager: Heather HurleyProject/Copy Editor: Karen A. GillTechnical Reviewer: Joshua SmithInterior Layout Tech: MPS LimitedCover Designer: Mike TanamachiIndexer: Valerie Haynes PerryProofreader: Megan Belanger 2015 Cengage Learning PTR.CENGAGE and CENGAGE LEARNING are registered trademarks of CengageLearning, Inc., within the United States and certain other jurisdictions.ALL RIGHTS RESERVED. No part of this work covered by the copyrightherein may be reproduced, transmitted, stored, or used in any form or by anymeans graphic, electronic, or mechanical, including but not limited tophotocopying, recording, scanning, digitizing, taping, Web distribution,information networks, or information storage and retrieval systems, exceptas permitted under Section 107 or 108 of the 1976 United States CopyrightAct, without the prior written permission of the publisher.For product information and technology assistance, contact us atCengage Learning Customer & Sales Support, 1-800-354-9706.For permission to use material from this text or product, submitall requests online at cengage.com/permissions.Further permissions questions can be emailed [email protected], Windows, and Internet Explorer are either registered trademarksor trademarks of Microsoft Corporation in the United States and/or othercountries.All other trademarks are the property of their respective owners.All images Cengage Learning unless otherwise noted.Cover background art: Eugene Sergeev/Shutterstock.com.Library of Congress Control Number: 2014933750ISBN-13: 978-1-285-85456-4ISBN-10: 1-285-85456-XCengage Learning PTR20 Channel Center StreetBoston, MA 02210USACengage Learning is a leading provider of customized learning solutionswith office locations around the globe, including Singapore, the UnitedKingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at:international.cengage.com/region.Cengage Learning products are represented in Canada by NelsonEducation, Ltd.For your lifelong learning solutions, visit cengageptr.com.Visit our corporate website at cengage.com.Printed in the United States of America1 2 3 4 5 6 7 16 15 14eISBN-10: 1-285-85457-8Today, the Internet is the most powerful source of informationthanks to the amazing efforts of many, including the following:nVinton Cerf, American Internet pioneer, who is recognizedas the father of the InternetnRobert Kahn, American engineer who, along with VintonCerf, invented the Transmission Control Protocol (TCP)and the Internet Protocol (IP), the communicationprotocols used on the InternetnTim Berners-Lee, British computer scientist also knownas the inventor of the World Wide Web (WWW)I dedicate this book to them and to my mother, Nita Harwani.The person I am today is a product of the moralvalues she taught me.AcknowledgmentsI am grateful to Heather Hurley, product manager at Cengage Learning, for believingin me and giving me an opportunity to create this work.Thank you to Karen Gill who, as my project editor and copy editor, offered a signifi-cant amount of feedbackthat improvedthechapters. Shedidfirst-class structuralandlanguageeditingandplayedavital roleinimprovingthequalityof informa-tion. Iappreciatehereffortsinenhancingthecontentsofthisbookandgivingitapolished look.I must thank Joshua Smith, the technical editor, for his excellent, detailed reviewing ofthe work and the many helpful comments and suggestions he made.Agreat bigthank-youtotheeditorial andproductionstaff andtheentireteamatCengage Learning who worked tirelessly to produce this book. I enjoyed working witheach of you. Thanks, too, to MPS Limited for making the book look good on pages.Ialsowanttomentionmyfamily, mysmall world. Tomywife, Anushka, andmywonderfulchildren, ChiragandNaman, thankyouforinspiringandmotivatingmeand above all for forgiving me for spending so much time on my computer.Speaking of encouragement, I must mention my dear students, who have been a goodteacherforme. Theirinterestingproblemsandquerieshelpmewritebookswithapractical approach.ivAbout the AuthorB. M. Harwani is the founder and owner of Microchip Computer Education (MCE),basedinAjmer, India, whichprovidescomputereducationinall programmingandwebdevelopingplatforms. HegraduatedwithaBEincomputer engineeringfromthe University of Pune, and he has a C Level diploma (Masters diploma in computertechnology) fromDOEACC, Government of India. As a teacher for more than20 years, he has developed the art of explaining even the most complicated topics ina straightforwardandeasilyunderstandable fashion. His publishedbooks includeFoundationJoomlapublishedbyFriendsOfED, jQueryRecipespublishedbyApress,CoreDataiOSEssentials publishedbyPackt, IntroductiontoPythonProgrammingand Developing GUI Applications with PyQT published by Cengage Learning, AndroidProgramming Unleashed published by Sams Publishing, The Android TabletDevelopers Cookbook (Developers Library) published by Addison-Wesley Profes-sional,and UNIX& Shell Programmingpublishedby OxfordUniversityPress,USA.To learn more, visit his blog at http://bmharwani.com/blog.vContentsIntroduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xivChapter 1 The .NET Framework. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1C# Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.NET Framework Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Common Language Runtime (CLR). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Common Type System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Common Language Specification. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Assembly Use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Visual Studio IDE Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Visual Studio Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Running a C# Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Using the Visual Studio IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Using the Command-Line Compiler. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Line-by-Line Explanation of Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Modification of the Main( ) Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Chapter 2 Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Identifiers and Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Predefined Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Predefined Value Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28viInteger Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28Floating-Point Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Decimal Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Character Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Bool Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32Nullable Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32Predefined Reference Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Implicitly Typed Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Implicit Conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39Explicit Type Conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40Boxing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Unboxing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41The is Operator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42The as Operator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Methods Defined by stream Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44The Predefined Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Console I/O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Sending Output to the Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Reading Input from the Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Comment Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51Windows Form Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59Chapter 3 Operators and Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Precedence and Associativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Adding Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63The typeof Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64The sizeof Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64Checked and Unchecked Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Increment and Decrement Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Sign Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70Equality Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Logical Boolean Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Logical Bitwise Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73Shift Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Compound Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Contents viiTernary Operator (Conditional Operator) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80The Math Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83Chapter 4 Decision-Making and Looping. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85The if-else-if Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86The switch Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90The Conditional Operator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96The while Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96The do-while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99The for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101The continue Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104The goto Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106Enumeration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111Chapter 5 Arrays and Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113Using Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114One-Dimensional Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119Using Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122Passing Command-Line Arguments to Main( ). . . . . . . . . . . . . . . . . . . . . . . . . 135Using StringBuilder. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Using ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148Chapter 6 Methods and Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149Return Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151Method Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151Method Invocation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151Method Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153Optional and Named Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157C# Parameter Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159Passing By Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160Passing By Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161Using Output Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162Sending Variable Length Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164viii ContentsYour Own Type: Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165Using Properties with Struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168Defining Arrays in Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169Using an Array of Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172Nested Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174Date and Time Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179Using the DateTime Properties and Methods . . . . . . . . . . . . . . . . . . . . . . . 179Using TimeSpan. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183Formatting Dates and Times. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184Custom Date and Time Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184Standard Date and Time Formatting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191Chapter 7 Classes and Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193The new Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195Public Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195Difference Between a Struct and a Class. . . . . . . . . . . . . . . . . . . . . . . . . . . 197Methods Defined in a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197Private Members. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199Parameter Passing by Value and Reference. . . . . . . . . . . . . . . . . . . . . . . . 201Output Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202Method Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205Use of Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206The this Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212Default Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213Parameterized Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215Copy Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219Constructor Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221Constructor Chaining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224Garbage Collection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227Static Classes and Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232Namespace Importing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235Namespace Nesting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237Namespace Alias Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238Internal Modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241Contents ixChapter 8 Inheritance and Polymorphism. . . . . . . . . . . . . . . . . . . . . . . . . . . 243Types of Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244Single Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245Multilevel Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253Hierarchical Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257Hybrid Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260Method Overriding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264Sealed Class and Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271Method Hiding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273Abstract Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276Abstract Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278Polymorphism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284Chapter 9 Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285Invoking Interface Members at the Object Level. . . . . . . . . . . . . . . . . . . . . . . 286Implementing Multiple Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288Handling Ambiguity When Implementing Multiple Interfaces. . . . . . . . . . . . 290Implementing an Interface Explicitly. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291Verifying Interface Implementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294Using the as Keyword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294Using the is Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294Implementing a Multilevel Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296Implementing Interface Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298Understanding How a Structure Implements an Interface. . . . . . . . . . . . . . . . 300Passing an Interface as a Parameter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301Returning an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304Chapter 10 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305Binary Operator Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306Adding a Constant to an Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309Adding Two Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311Unary Operator Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312true and false Operator Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315Comparison Operators Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316Conversion Operators Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323Creating an Implicit Conversion Operator. . . . . . . . . . . . . . . . . . . . . . . . . . 324Creating an Explicit Conversion Operator . . . . . . . . . . . . . . . . . . . . . . . . . . 324Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328x ContentsChapter 11 Delegates and Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329Delegates Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329Declaring Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329Instantiating Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330Invoking the Referenced Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331Instance Versus Static Method Targets. . . . . . . . . . . . . . . . . . . . . . . . . . . . 334Multicast Delegates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335Covariance and Contravariance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342Generic Delegate Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347Anonymous Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351Difference Between Delegates and Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . 352Event Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354Declaring an Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354Event Accessors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363Chapter 12 Generics and Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365Standard Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367IEnumerators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368Hashtable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375SortedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377BitArray. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378Stack. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381Generics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382Generic Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388Generic List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396SortedSet. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404LinkedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408Chapter 13 Managing Errors and Exceptions. . . . . . . . . . . . . . . . . . . . . . . . . . 409Introducing Errors and Exceptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409The Exception Hierarchy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410Keywords Used in Exception Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . 411Using Multiple try Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415Using Multiple catch Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418Throwing an Exception. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421Contents xiNesting try Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424Creating Your Own Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426Using the checked/unchecked Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430Chapter 14 Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431Introduction to Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431Using the Main Thread. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432Creating Child Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432Life Cycle of a Thread. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438Multithreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444Ensuring Exclusive Operations Using Monitors . . . . . . . . . . . . . . . . . . . . . . 447Using the Lock Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449Interrupting a Thread. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452Chapter 15 Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453Introducing Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454Handling Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457Reading a File Randomly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462Reading and Writing Primitive Types in Binary Format . . . . . . . . . . . . . . . . . . 465Using BinaryWriter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465Using BinaryReader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466Performing Character-Based File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468Using StreamWriter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468Implementing TextWriter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472Using StreamReader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473Implementing TextReader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475Using StringReader and StringWriter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476Reading an Entire File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478Holding Data Temporarily Using MemoryStream. . . . . . . . . . . . . . . . . . . . . . . 480Managing a Directory Using DirectoryInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484Chapter 16 ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485Examining the Major Components of ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . 486Connecting or Creating a Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489Accessing Data from the Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498Creating a Connection to the Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499Opening the Connection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502Creating a Command Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503Closing the Connection and Releasing the Resources. . . . . . . . . . . . . . . . . 505Displaying the Table Data Through GridView. . . . . . . . . . . . . . . . . . . . . . 510xii ContentsInserting Rows in a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516Using Parameters with the Command Object . . . . . . . . . . . . . . . . . . . . . . . 521Calling Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522Updating a Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532Chapter 17 LINQ Queries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533Implicitly Typed Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534Object and Collection Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535Lambda Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536Extension Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538Anonymous Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540LINQ Categories. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541LINQ to Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541LINQ to XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544LINQ to SQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553Chapter 18 Web-Based Application Development in .NET. . . . . . . . . . . . . . . 555Examining the Visual Studio Toolbox. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556Building Your First Web Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560Using the DropDownList Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570Understanding the AutoPostBack Property . . . . . . . . . . . . . . . . . . . . . . . . 573Using the ArrayList Class to Display Data in DropDownList . . . . . . . . . . . . 577Using the CheckBox Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578Using the RadioButton Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585Using the ListBox Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589Using the LinkButton Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595Using the HyperLink Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598Using the ImageButton Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603Working with WCF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605Creating a Client Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619Chapter 19 .NET Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621Using Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621Private Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622Shared Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622Creating and Using a Shared Assembly. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .633Contents xiiiIntroductionThis bookprovides athoroughguide tothe most valuable features of C#5.0. Itexplains object-oriented programming (OOP) principles and their benefit in develop-ing real-world applications, and it integrates in-depth OOP fundamentals when devel-opingcodeinC#. Itprovidesessential, straightforwardinformationtohelpreadersmaster the core capabilities of Visual C# 2013 and explores creating and using advancedclassfeaturessuchasgenerics, collections, andoperatoroverloading. Readerswill digdeep into web services, LINQ, multiple threading, and security features. This book alsoofferscompletecoverageof .NETfeatures, includingassemblies, interfaces, delegates,events, web application development, and ADO.NET.What Youll Find in This BookThis book focuses on hands-on projects. It successfully presents readers with a com-prehensive guide covering each major skill required for developing apps using C# 5.0.Heres what youll find in this solid, comprehensive reference:nPlenty of running examplesnA progression from easy examples to deeper, complex topicsnAn explanation of object-oriented programming principles and their benefit indeveloping real-world applicationsnCoverage of inheritance, polymorphism, interfaces, operator overloading,delegates, and eventsxivnApplication of generics and collections, managing errors and exceptions,implementing multiple threads, using ADO.NET, accessing information usingLINQ queries, and developing web-based application development in .NETnAll topics that are required for developing apps in C# 5.0Who This Book Is ForThe bookaddresses intermediate toadvancedusers, teaching different aspects ofobject-oriented programming in detail. The book explores valuable features of C# 5.0withrunningexamples. Itbeginswithfundamentaltopicslikedatatypes, operators,expressions, branching and looping statements, arrays, and strings. After these funda-mental topics, it gradually digs into the complex topics of reusability of code throughclasses, objects, inheritance, and polymorphism. The book covers interfaces, operatoroverloading, delegates, and events. Finally, it applies generics and collections, manageserrors andexceptions, implements multiple threads, uses ADO.NET, andaccessesinformation using LINQ queries.The book is beneficial for developers and instructors who want to learn or teach C# 5.0programming. For practical implementation, the book also explains web-based appli-cation development in .NET.How This Book Is OrganizedThebookteachesdifferentaspectsofobject-orientedprogramming. Heresabreak-down of topics covered by chapter.Chapter1, The.NETFrameworkCoversintroductiontoC#, .NETFramework,CLR, CTS, CLS, and Assembly. It also introduces Visual Studio IDE, the requirementstoinstall Visual Studio, andstepstorunaC#program. Thechapterconcludesbyusing the Visual Studio IDE to develop C# programs.Chapter2, DataTypesCoversprogrammingfundamental structslikeidentifiers,keywords, variables,and constants. You learn about predefineddata types, includinginteger, floating-point, decimal, character, bool, nullable, and string types. In addition,the chapter explains implicitly typed variables, implicit type conversion, explicit typeconversion, and streams. You perform console I/O, read input from the console, writecomments, and create a Windows Form application.Chapter3, OperatorsandExpressionsCoversoperators, precedenceandassocia-tivity, and the typeof, sizeof, checked, and uncheckedoperators. You learn touse arithmetic, increment, and decrement operators along with sign, relationalIntroduction xvequality, logical Boolean, logical bitwise, shift, assignment, andternary operators.Finally, you learn about the Math class.Chapter 4, Decision-Making and LoopingCovers conditional statements thatinclude if-else-if and switch. You learn to use the conditional operator and var-iousloops. Thechapterexplainsthewhileloop, do-whileloop, forloop, gotostatement, nested loops, and enumeration.Chapter 5, Arrays and StringsCovers both one-dimensional and multidimensionalarrays. Also, youlearntoinitializeanarrayandusethe foreachloop. Inaddition,this chapter explains usingstrings, passingcommand-line arguments tothe mainmethod, using StringBuilder, and using ArrayList.Chapter 6,Methods and StructuresCovers methods, method parameters, methodinvoking, and method overloading. You learn about using optional and named para-meters, C# parameter modifiers, passing by value, passing by reference, output para-meters, and variable length parameters. The chapter also explains defining your owntype (structures), using properties with struct, defining arrays in structures, and usingarrayofstructuresandnestedstructs. Finally, thechaptercoversthedateandtimestructure, DateTimepropertiesandmethods, TimeSpan, dateandtimeformatting,and application of custom and standard date and time formatting.Chapter7, ClassesandObjectsCoversclass, applicationof thenewoperator,accessing of public members, the difference between a struct and a class, methods in aclass, and the return statement. The chapter also explains using method parameters,usingprivatemembers, passingparametersbyvalueandbyreference, usingoutputparameters, using method overloading, implementing encapsulation, using properties,and implementing the this keyword. Also covered are default constructors, parame-terized constructors, copy constructors, constructor overloading, and constructorchaining. Finally, the chapter explains garbage collection, destructors/finalizers, staticclasses and members, static classes and constructors, namespace importing, namespacenesting, creation of a namespace alias, and the internal modifier.Chapter8, InheritanceandPolymorphismCoverssingleinheritance, useofpro-tectedmembers, andbaseclassconstructorcalling. Thechapteralsoexplainsmulti-level inheritance, hierarchical inheritance, hybrid inheritance, method overriding,virtual methods, sealedclassandmethods, methodhiding, abstractclasses, abstractproperties, and polymorphism.Chapter 9, InterfacesCovers invoking interface members at the object level, imple-mentingmultipleinterfaces, implementinginterfacesexplicitly, andverifyinginter-faceimplementation. Thechapter alsoexplains implementingmultilevel interfaces,xvi Introductionimplementing interface properties, understanding howa structure implements aninterface, passing an interface as a parameter, and returning an interface.Chapter 10, Operator OverloadingIntroduces binary operator overloading, unaryoperatoroverloading, additionof aconstant toanobject, additionof twocomplexnumbers, true and false operator overloading, comparison operators overloading,comparisonofobjectsforequality, conversionoperatorsoverloading, creationofanimplicit conversion operator, and creation of an explicit conversion operator.Chapter 11, Delegates andEventsCovers declaringandinstantiatingdelegates,invoking the referenced method, understanding instance versus static method targets,using multicast delegates, implementing covariance and contravariance, defininggeneric delegate types, using the anonymous method, distinguishing between delegatesand interfaces, handling events, declaring an event, and declaring event accessors.Chapter 12, Generics and CollectionsCovers standard interfaces, IEnumerators,thegenericcollectionclasses, thehashtable, SortedList, BitArray, thestackandqueue, generic types, generic collections, the Generic List collection,Queue, Stack, SortedSet, Dictionary, and LinkedList.Chapter 13, Managing Errors and ExceptionsCovers errors, exceptions, the excep-tionhierarchy, andkeywordsusedinexceptionhandling. Thechapteralsoexplainsusingmultiple tryand catchblocks, catchingalltypesofexceptions, throwinganexception, rethrowing an exception, nesting try blocks, creating your own exception,and using the checked/unchecked operator.Chapter 14, ThreadsIntroduces the main thread, child threads, use of the Threadclass, andthelifecycleofathread. Thechapteralsoexplainsthreadpropertiesandmethods, multithreading, exclusiveoperationsusingMonitor, theLockstatement,and thread interruptions.Chapter 15, StreamsIntroduces streams, C#I/Oclasses, filehandling, openingandclosingof afile, randomreadingof afile, positioningof thefilepointerusingthe Seekmethod, reading andwriting of primitive types inbinary format, anduse of BinaryWriterandBinaryReader. Youcreate character-basedfile I/O,use StreamWriter, utilize the using statement, implement TextWriter andTextReader, and use StreamReader and StringWriter. Also, you learn to readanentirefile, holddatatemporarilyusing MemoryStream, andmanageadirectoryusing DirectoryInfo.Chapter16, ADO.NETIntroducesmajorcomponentsofADO.NET, dataprovi-ders, creationandconnectionto adatabase, creationof adatabasetable, dataaccessfrom a database, connection to the server, and opening of the connection. The chapterIntroduction xviialso explains creating a Command object, executing commands, closing the connection,and releasing the resources. Finally, you learn to use try catch finally, admin-ister the using keyword, display the table data through GridView, insert rows into atable, use parameters with the Command object, call stored procedures, and update thedatabase table.Chapter 17, LINQQueriesCovers LINQ, implicitly typedlocal variables, andobject andcollectioninitializers. Youlearntouselambdaexpressions, anonymousmethods, extension methods, anonymous types, and LINQ categories.Chapter 18, Web-Based Application Development in .NETExplains Visual Studiotoolbox, construction of your first web application, and use of the CheckBox,RadioButton, ListBox, LinkButton, and HyperLinkcontrols. Thechapteralsoexplainsusingthe ImageButtoncontrol, workingwithWCF, andcreatingaclientapplication for web services.Chapter 19, .NET AssembliesExplains creation and use of a shared assembly.Companion Website DownloadsYou may download the companion website files from www.cengageptr.com/downloads.xviii IntroductionChapter 1The .NET FrameworkThis chapters topics include the following:nC# introductionn.NET Framework structurenAssembly usenVisual Studio IDE overviewnVisual Studio installationnRunning a C# programnLine-by-line explanation of codenModification of the Main() methodYoull begin your journey with an introduction to C#.C# IntroductionC#was createdat Microsoft inthelate1990s, andits chief architect was AndersHejlsberg. As anobject-orientedlanguage, C#supports dataencapsulation, inheri-tance, polymorphism, andmethodoverriding. Itisapowerful andsimplelanguageforbuildinginteroperable, scalable, androbustapplications. Several ofC#sfeaturesare mentioned next:nWith C#, you can develop console windows as well as web applications.nC# supports garbage collection and automatic memory management.1nC# includes native support for the Component Object Model (COM) andWindows-based applications.nTo avoid redundancy, the values of the primitive data types are automaticallyinitialized to zeros, and reference types like objects and classes are initialized tonull.nC# produces portable code.nIts programs execute in a secure, controlled, runtime environment.nC# supports generics, partial types, and anonymous methods that expand thescope, power, and range of the language.nIt also supports language-integrated query (LINQ) and lambda expressions. LINQenables you to write database queries in C# programming. Lambda expressionsare used in LINQ expressions for efficient coding.C# doesnt support unsafe type casts or pointers, and it doesnt accept 0 or 1 for Bool-ean values false and true, respectively.Because C# automatically uses the .NET class library and it is automatically portable toall .NET environments, the next section covers the .NET framework and its relation-ship with C#..NET Framework StructureThe .NET framework is a software development framework from Microsoft. It is a col-lectionof tools, technologies, andlanguagesthat providesanenvironment tobuildanddeployrobust enterpriseapplications easily. It alsosupports thedevelopmentand execution of highly distributed, component-based applications. The .NET Frame-worksitsontopofanoperatingsystemthatincludesWindowsVista, Windows7,Windows 8, andWindows Server 2008. At the base of the .NETFramework isthe CommonLanguage Runtime (CLR) that manages the executionof the code(seeFigure1.1). Applicationscompiledforthe.NETFrameworkarenot compileddirectly to native code but into an intermediate language called Microsoft IntermediateLanguage (MSIL). The CLR Just-In-Time (JIT) compiler compiles the MSIL code intonativecodebeforeitisexecuted. Thenextlayerupisthe.NETBaseClassLibrary,which contains classes and interfaces used for building applications. Above this layeris the ADO.NET and XML layer that supports the tasks related to data access, manip-ulating, parsing, andgenerating XML. The next layer is ASP.NETandWindowsForms, which build robust web applications and the standard Windows applications.Thelayeralsodevelopsandconsumeswebservices. .NETsupportscross-languageintegration. In other words, the code can be written in different programming2 Chapter 1 n The .NET Frameworklanguagesthat .NETsupports. But different programminglanguageshavedifferentconstructs. Formakingthelanguagescompatible, CommonLanguageSpecification(CLS) isused. TheCLSdefinesthereasonablesubset of theCTS: theshareddatatype that helps in cross-language integration.Because CTS is quite flexible, many languages adapt to the .NET platform. This meansthatyoucandevelopwebapplicationsinseveral programminglanguages, includingVisual Basic, C++, C#, JScript, and J#.Figure 1.1Structure of .NET Framework. 2015 Cengage Learning..NET supports the following features:nInteroperability.NET includes a large library and supports several program-ming languages, allowing you to write code in different languages.nCommon Language RuntimeThis is part of the .NET Framework thatprovides a runtime environment for the execution of code written in .NETlanguages. It manages the execution of .NET code, enables debugging andexception handling, and makes programs portable.nLanguage independence.NET supports several programming languages,including VB.NET, C#, J#, and C++, and the code in all the supported languagesis compiled into Common Language Infrastructure (CLI) specifications, enablingyou to exchange data types between programs developed in different languages..NET Framework Structure 3nDevelopment for dynamic web pages.NET offers an integrated support fordeveloping dynamic web pages, using a new technology.nBase Class LibraryThis library contains classes, value types, and interfaces thatare often used in application development. The classes are organized as name-spaces, and the developers can easily use them just by including these namespacesin their programs.nADO.NETADO.NET provides access to relational databases and several datasources, such as Microsoft SQL Server and XML. You can use ADO.NET toconnect to these data sources and retrieve, manipulate, and update data.nAJAX.NET supports AJAX, which developers can use to create highlyresponsive web applications with minimal effort.nWeb services.NET has fully integrated support for developing web services.nSecurity.NET uses the assembly for code sharing instead of traditional DLL,which not only supports versioning but also implements security and allows onlyauthorized categories of users or processes to call designated methods of specificclasses.Followingaresomeimportant termsrelatedto.NETthat youneedtounderstandbefore you move ahead.Common Language Runtime (CLR)The CLR is a runtime environment of the .NET Framework that manages the execu-tionof.NETcodeandconvertsthesourcecodeintotheMSIL. TheMSILisnotanexecutable code but a portable assembly code; it is not dependent on a specific CPU.When the program is run, only the MSIL code is converted into executable code. TheCLR activates the JIT compiler to convert MSIL into executable code. In other words,theMSILcanruninanyenvironment forwhichtheCLRisimplemented, therebyimplementing portability.The CLR manages the code while executing. It also provides various services requiredinexecutionof anapplication, suchas memorymanagement, garbage collection,threadmanagement, exceptionhandling, andsecuritychecks. Furthermore, itman-ages versioning, deployment support, anddebugging. Finally, it locates, loads, andmanages different .NET types.4 Chapter 1 n The .NET FrameworkNoteThe code that is executed under the control of the CLR is known as managed code. The managed code issupposed to produce an MSIL file targeted for the CLR and use the .NET Framework library so that it canbenefit from memory management, mixing languages, better security, and versioning control.Common Type SystemCommon Type System (CTS) is a formal specification that documents how types aredeclared, used, and managed so the CLR can use them. Every language that is runningon the .NET platform has a base set of data types that CTS provides. CTS ensures thatthe data types of objects written in various languages can interact with each other.CTS supports both value types and reference types.Value types represent built-in types likeint, float, andchar, user-defined types, andenumerations. Valuetypes directlycontainthedataof therespectivetypeandnoreference. Instances of value types are allocated on the stack.Reference types store a reference to the values memory address and are allocated onthe heap. Reference types can be arrays, pointer types, interface types, class types, ordelegates.NoteC# has 15 predefined types, 13 value types, and 2 reference types.Common Language SpecificationThe Common Language Specification (CLS) is a subset of CTS that ensures interoper-ability between the languages in the .NET environment. It defines the rules to supportlanguageintegrationsothattheprogramswritteninany.NET-compliant languagecan interoperate.Assembly UseAssembliesarebasicallythecompiledcodein.NETthatcontainsthecodeinMSILandalot of otherinformationthat allowsyoutoperformseveral tasks, includingdeployment, versioncontrol, reuse, activationscoping, andsecuritypermissions. Infact, every application in .NET is deployed as an assembly; in other words, the entire.NETcode oncompilationis convertedintoanintermediate language code andis stored as an assembly. There are two kinds of assemblies: executables that have the.exefileextension, andlibraryassembliesthathavethe.dllfileextension. TheseareAssembly Use 5also known as class libraries because they contain classes that you can directly use inyour programs.An assembly is a collection of class modules presented as a single .dll or .exe file. Theassembly contains metadata that provides version information along with a completedescription of methods, types, and other resources.The metadata includes Manifest, which stores identification information, public types,and a list of other assemblies that are used in current assembly.Each assembly has a 128-bit version number that is presented as a set of four decimalpieces: Major.Minor.Build.Revision. For example, an assembly might have the versionnumber 8.0.1.7.Theconceptof versioningenables the developersto installnew ver-sionsofthecomponentsthatarenotbackwardcompatible. Anassemblyonlyusestypes from the same assembly that it was built and tested with. If an assembly uses atype from version 8.0.1.7, for example, it does not use the same type from any otherversion. This helps developers in a couple of ways. First, the developers can define thesametypeintwoassemblieswithout fearof collisions. Second, thedeveloperscaninstall anewversionofthecomponent(s)thatisnotbackwardcompatiblewithoutfear of earlier applications that stop working.There are two types of assemblies: private and shared. A private assembly is used byonly one application, whereas a shared assembly is shared among several applications.By default, when a C# program is compiled, it produces a private assembly. The pri-vateassemblyisplacedinthesamefolderasthecallingapplication. Becauseeachapplication has its own copy of the assembly, there is no versioning problem in caseofprivateassembly. Inasharedassembly, toavoidacollision, youassignauniquename to it by using a strong name. A strong name is a combination of a filename, apublic key, a version number, and a culture (locale information).Private assemblies and shared assemblies are structurally identical. The real differencebetween private and shared assemblies depends on the way they are named and ver-sioned and where they are deployed. Here are several distinctions between the two:nMultiple applications can use a shared assembly. Only one application can use aprivate assembly.nA shared assembly has to be registered in Global Assembly Cache (GAC). Theresno need to register a private assembly; it is stored in the respective applicationsdirectory.nA strong name has to be created for a shared assembly. A strong name is notrequired for a private assembly.6 Chapter 1 n The .NET FrameworknA shared assembly can have multiple versions that are not backward compatible.If a private assembly has multiple versions that are not backward compatible, theapplication stops working.nBy default, all assemblies that you create are considered private assemblies. Whenyou register a private assembly in GAC with a strong name, it becomes a sharedassembly. The common utility that registers the assembly with a strong name inGAC is gacutil.exe, which is shipped with the .NET Framework.After being introduced to C#, .NET, and its differentterms, its time to take a quicklook at the steps required for running a C# program.Visual Studio IDE OverviewTo get started programming in C#, you need a compiler and an editor. Many editorsand IDEs are available for this purpose. One of them that is popularly used is calledVisual Studio. Visual Studio is Microsofts integrated programming environment thatenablesyoutoedit, compile, run, anddebugaC#program, allinoneplace. VisualStudio is basically a collectionof software tools that is availablein multiple editions:Professional, Premium, and Ultimate.The Professional edition includes the basic features of the IDE to build applications onall .NET languages, including Visual Basic, C#, F#, and C++. It supports the writing,debugging, andtestingof code. It enablesdevelopment of all typesof applications,including console, Windows, web, Windows Services, Cloud, WPF, Silverlight, Data-base, Office, and much more. In addition, it supports features that include unit testing,multicoredevelopment, officedevelopment, refactoring, accesstoTeamFoundationServer (TFS), and Class Designer.ThePremiumeditionisanenhancedformofProfessionaleditionthattargetscom-mercial enterpriseapplicationdevelopment. It supportsdatabasedevelopment toolsand provides additional tools to verify, test, and check code. It also supports featuresthat include profiling, code metrics, and user interface tests.The Ultimate edition is an enhanced form of Premium edition that includes almost alltools required to develop different types of applications.Visual Studio is also available in Express editions for developing applications for theweb, Windows 8, andWindows Phone. The Express editions are free. Althoughtheyre not bundled with powerful tools, the Express editions are sufficient for devel-oping small applications. They also have full language support and access to the .NETFramework libraries.Visual Studio IDE Overview 7Visual Studio InstallationVisual Studio is compatible to 32-bit (x86) as well as 64-bit (x64) architectures. It sup-ports operating systems that include Windows 7 (x86 and x64), Windows 8 (x86 andx64),WindowsServer2008R2(x64), andWindowsServer2013(x64). Itrequiresa1.6GHzorfasterprocessor, 1GBRAM, 10GBavailableharddiskspace, 5400RPMhard drive, and DirectX 9-capable video card running at 1024 768 or higher displayresolution.Visithttp://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspxto download the desired Visual Studio edition. An executable setup file is then down-loaded to your computer. This book is being written while using Microsoft Visual Stu-dio Express 2013 for Web.1. Double-click the downloaded executable file to initiate the install of VisualStudio 2013.2. Navigate to the location youd like to install Visual Studio. The screen displaysthe hard disk space that the setup requires.3. Agree to the license terms and conditions that are required before proceedingwith the installation.4. Click Next to move further. The next screen displays the list of optional featuresthat you can install.5. Select the check boxes of the desired features or choose Select All to select all thefeatures.6. Click the Install button. The next screen shows the progress of acquiring andapplying the installation files.7. Click the button to launch Visual Studio when the application process iscompleted.When launched for the first time, Visual Studio displays a dialog box that prompts youto choose the default environment settings. Choose the General Development Settingsoptionfromthelistofavailableenvironment settingsandclickontheStartVisualStudio button. The general development setting is applied, and your Visual Studio isready for the application development. The first page that is displayed is known as theStart Page, and it is shown in Figure 1.2. As you can see in the figure, the Start PagecontainsalistoflinkstoVisualStudioresourcesandweb-basedresources. Youcanreturn to the Start Page by selecting View, Start Page.8 Chapter 1 n The .NET FrameworkFigure 1.2The Start Page after launching Visual Studio.Used with permission from Microsoft.The left column in the Start Page contains a Start section that displays links for build-ing new applications. Below the Start section is the Recent section, which displays thelinks to projects that were recently created or modified. The right column contains thelinkstoinformationabout newfeaturesandimprovementsimplementedinVisualStudio Express 2013 for Web. The column also contains the links to the new informa-tion in Web Development and various learning resources.NowthatyouvelearnedhowtoinstallVisualStudioIDE, thenextsectionexploresthe steps required for running a C# program.Running a C# ProgramThere are two ways to create, compile, and run a C# program. The first method is touse the Visual Studio IDE, and the second method is to use the command-line com-piler csc.exe. First youll look at using the Visual Studio IDE.Running a C# Program 9Using the Visual Studio IDETo write a C# program in the Visual Studio 2013 IDE, launch it and select File, NewProject or press Ctrl+Shift+N. A list of .NET-supported languages is displayed:nVisual BasicDevelopers who are familiar with Visual Basic or a similar lan-guage use this language to build type-safe, object-oriented applications.nVisual C#This option is designed for developers who are familiar with C-stylelanguages, such as C, C++, and Java. Developers can use this language to rapidlydevelop type-safe, object-oriented applications.nVisual C++Specifically designed for C++ developers, this language can be usedto build .NET managed applications as well as independent Windows-basedapplications that do not require .NET support.nVisual F#This language makes the task of developing applications related toscience, engineering, and mathematical computations much easier.Because you are interested in developing C# applications, select the Visual C#language from the left pane. After selecting a language, a list of project types that aresupported by that language is displayed on the right. Heres a brief description of com-monly used project types:nWindows Forms ApplicationCreates a standalone WindowsapplicationGUI-based application based on Windows Forms technology.nWPF ApplicationCreates a project that uses a powerful Windows PresentationFoundation framework.nConsole ApplicationCreates command-line application executables. Theseapplications dont support a graphical user interface and are executed at thecommand prompt.nASP.NET Web Forms ApplicationCreates web applications that can bedeployed to a web server.nClass LibraryCreates reusable classes and components that can be shared withother projects. Specifically, this template enables you to build assemblies that canbe shared with other applications.nPortable Class LibraryCreates and manages assemblies that work on morethan one .NET Framework platform. That is, the assemblies can work on .NET 4,.NET 4.5, Silverlight 5, Windows Phone 8, and other platforms withoutmodifications.10 Chapter 1 n The .NET FrameworknASP.NET MVC 3/4 Web ApplicationCreates a web application based on aweb application development framework that splits applications into three layers:the model, the view, and the controller.nSilverlight ApplicationCreates applications based on the application frame-work Microsoft Silverlight for developing rich Internet applications. These appli-cations support multimedia, graphics, animation, languages, and developmenttools.nSilverlight Class LibraryCreates a Silverlight class library project that can beused by Silverlight applications.nWindows Forms Control LibraryCreates custom controls to use on WindowsForms.Fromthelistofprojecttypesdisplayed, selecttheConsoleApplicationtype. Specifythe name ofthe applicationasConsoleApp, and thenselect theOK button(shown inFigure 1.3).NoteIf you dont find the Console Application type in your Visual Studio IDE, select the Class Library option.Figure 1.3Selecting the Console Application template for creating a new application.Used with permission from Microsoft.Running a C# Program 11Thenewconsoleapplicationappears, asshowninFigure1.4. Inthefigure, noticecertain windows and toolbars. Heres a description of them:nSolution ExplorerIn the Solution Explorer window (docked on the right side),you can see the default files that are created by the IDE. Only the editable files aredisplayed; other IDE-generated files are hidden by default. To display all the files,including the hidden ones, click the Show All Files icon located at the top of theSolution Explorer window. If its hidden, select View, Solution Explorer to makethe Solution Explorer window visible. Each project type that is selected whilecreating a new project provides a specific default code. The main file of the con-sole application is Class1.cs, and it automatically shows up in the Editor windowwhen the application is loaded. The Properties folder provides access to theproject-level settings. References are a collection of assemblies that the applicationdepends on. The project template automatically adds to the project references tocommonly used class libraries (see Solution Explorer in Figure 1.4).NoteVisual C# files use the .cs filename extension, which is short forC#.nProperties WindowLocated below the Solution Explorer, this window displaysthe properties for the currently selected form, control, or object in the IDE.Properties display information about the selected item, such as its ID, text, size,and color. The left column lists the properties, and the right column displaysthe value of each property. You can modify the properties of the selected itemas per your requirements, and the IDE automatically generates the related code.You can sort the properties either alphabetically by clicking the Alphabetical iconor category wise by clicking the Categorized icon. If the Properties window ishidden, select View, Properties Window to display it.12 Chapter 1 n The .NET FrameworkFigure 1.4Visual Studio IDE showing default code for console application.Used with permission from Microsoft.nError List WindowThis window displays errors in the code if any exist andhelps in pointing out and removing them. After you double-click the error that isshown in this window, the cursor jumps to the location of the error in the sourcecode so you can correct it. The code that is causing the error is specificallymarked with red wavy lines. The location of the error is specified as a line num-ber. By default, line numbers arent displayed in the VS text editor. To display theline numbers, select Tool, Options. From the Options dialog box, expand the TextEditor Node and select C# node and check the Line Numbers check box, asshown in Figure 1.5.Running a C# Program 13Figure 1.5Options dialog box.Used with permission from Microsoft.nToolBoxThis shows the tools, also called controls, divided into related catego-ries. If its invisible, ToolBox can be displayed by selecting View, Toolbox. To usea control in GUI applications, just drag it from the desired category and drop iton the form, and the IDE automatically generates code for that tool. By default,the AutoHide feature is enabled for the ToolBox; consequently, the ToolBoxappears when you click its title. The ToolBox appears over the Design window(in case of Forms) or the Editor window, thereby hiding the controls behind theToolBox. Also, it makes it difficult to add controls to the form. To switch off theAutoHide featurein other words, to keep the ToolBox visible on the left of theDesign or Editor windowclick the pushpin button in the upper-right corner ofthe ToolBox.nMenu Bar and ToolbarMenu Bar contains the groups of related commandsused for managing and manipulating the IDE and the applications. When youchoose a menu item from a menu, the designated task for that menu item is per-formed. The commonly used menu items are provided in the form of tools in thetoolbar. The tools in the toolbar appear as icons. When you hover the mouse, aToolTip appears indicating the task that the tool can perform.14 Chapter 1 n The .NET FrameworkThe default code provided in the file Class1.cs is shown in Listing 1.1.Listing 1.1 Default Code in Class1.cs Fileusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp{public class Class1{}}You want to display the messageHello World! through this application. For this, addtwostatements, Console.WriteLineandConsole.ReadLinewiththeMainmethod, totheprecedingcode. TheMainmethodisanentrypoint of aC#consoleorWindowsapplication. The file after adding the two statements appears as shown in Listing 1.2.Only the code in bold is newly added; the rest of the code is default.Listing 1.2 Code Written in Class1.cs Fileusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp{public class Class1{static void Main(string[] args){Console.WriteLine("Hello World!");Console.ReadKey();}}}Running a C# Program 15The Console.WriteLine() method is meant for displaying a message or a result of pro-cessing on the screen. In contrast, theConsole.ReadKey() method is used for getting akey from the user through the keyboard.Basically, when you run a console-based application in the Visual Studio IDE, the out-put appears in a console window, and control immediately comes back to Visual Stu-dio IDE. (That is, the console window does not wait for sufficient time for the user tosee the program output and goes back to the IDE immediately; consequently, you willnot be able to view the output of the program.) To make the console window wait forenough time, enabling the user to view the output of the program, you need to add theConsole.ReadKey()methodtotheprogram. TheConsole.ReadKey()methodwaitsforthe user to press any key on the keyboard, thereby displaying the output of the pro-gram. Only when the user presses a key does the console window disappear. To com-pile and run the program, select Debug, Start Debugging or press the F5 key. You getthe output shown in Figure 1.6.NoteIf the application type chosen is ClassLibrary, then we need to set its output type toConsoleApplication. For doingso, right-clicktheproject inSolutionExplorer andselect thePropertiesoption.FromtheProperties dialog, clicktheApplicationtab, andintheOutput Typedrop-down, select theConsole Application option.Figure 1.6Output of the console application.Used with permission from Microsoft.You can see that the text message Hello World! is displayed on the screen.Now that you understand the way C# runs in the Visual Studio IDE, the next sectioncovers how to run C# through the command-line compiler.16 Chapter 1 n The .NET FrameworkUsing the Command-Line CompilerTheC#command-linecompilerisconvenient forcompilingandrunningC#pro-grams because you dont have to create a project for the program. So it is a bit fasterand easier than using the IDE. Simply type the program in an editor, say Notepad.exe,and save the file with the extension.cs in any of the folders on your disk drive. Forexample, type the code as shown in Listing 1.3 in Notepad and save it with the nameHelloWorld.cs.Listing 1.3 Code Written in HelloWorld.cs Fileusing System;class HelloWorldClass{static void Main(string[] args){Console.WriteLine("Hello World!");}}To compile the program through the C# command-line compiler csc.exe, you need toopenacommandprompt windowthat is configuredfor Visual Studio. Select theDeveloperCommandPrompt forVS2013optionfromtheStart menu. Thereafter,using theCD command, go to the folder where you have saved theHelloWorld.cs file.At the command prompt, execute the C# compiler csc.exe, specifying the name of thesource file, as shown here:D:\CSharpBookCode>csc HelloWorld.csThe csc compiler shows errors in your program if any exist. If there are no errors, thecsc compiler successfully compiles the program and creates a file called HelloWorld.exethat contains the MSIL version of the program (see Figure 1.7). Although MSIL is notexecutable code, it is still contained in an .exe file.Figure 1.7Compiling and running the C# program HelloWorld.Used with permission from Microsoft.Running a C# Program 17The Common Language Runtime automatically invokes the JIT compiler after execut-ingthefileHelloWorld.exe. Toruntheprogram, justtypeitsnameatthecommandprompt, as shown here:D:\CSharpBookCode>HelloWorldWhen the program runs, the following output is displayed:Hello World!NoteIf thecsc command does not work, the path is not set. Set the following path for csc.exe:C:\Windows\Microsoft.NET\Framework\vX.X.XXX.Line-by-Line Explanation of Code1 using System;2 class HelloWorldClass3 {4 static void Main(string[] args)5 {6 Console.WriteLine("Hello World!");7 }8 }Line 1 indicates that the program is using the System namespace. A namespace definesalogical groupingthatorganizesrelatedclasses, structures, delegates, enumerations,interfaces, and other types. The idea of enclosing these members in namespaces is toavoid name conflicts. A class named A defined in namespace1 does not conflict with theclass named A defined in namespace2. By using or importing a namespace in a program,you enable the importing program to access the members organized in the namespace.Becauseyouareusingthelibraryclass System.Consoleinyour program, the usingSystem; statement allows you to refer to this class simply as Console (without qualifyingit by namespace as System). That is, you can access any of the members defined in theSystemnamespacedirectlywithout qualifyingit withthe Systemnamespace if youimport it at the top of the program with theusing statement. Most of the .NET typesare defined in the standard System namespace. In this program, the goal is to access theWriteLine() method of theConsole class defined in theSystem namespace for display-ingatextmessageonthescreen. TheConsoleisthe.NETbaseclasses. BesidestheConsoleclass, therearemanyotherclassesdefinedintheSystemnamespacethatareused in almost every C# program. Therefore, you will be importing the System18 Chapter 1 n The .NET Frameworknamespace with theusing statement in almost all C# programs. You will learn aboutnamespaces in detail in Chapter 5, Arrays and Strings.NoteThe most fundamental namespace used in C# applications is System. It is not possible to build a functionalC# application without using the System namespace.Line 2 uses the keyword class to declare that a new class is being defined. The class isused for encapsulation. The name of the class isHelloWorldClass. The class definitionbegins with the opening curly brace ({) and ends with the closing curly brace (}). Theelements between the two braces are members of the class.Line 4 defines theMain() method and is the entry point of a C# program. (That is, itbeginsitsexecutionfromtheMain()method.)Themethodhasthestaticmodifier,which means it can be called before an object of this class is created. This is becauseMain() is called at program startup. The keyword void indicates that the Main() methoddoes not return a value. The Main() method has a single parameter: an array of strings(string[]args). Youcanusethis parameter for passingcommand-linearguments.You will be learning about command line arguments in detail in Chapter 4, Decision-Making and Looping. The empty parentheses that follow Main indicate that no infor-mationispassedtoMain(). Theopeningcurlybraces({)signalthestartofMain( )sbody. All thecodethat comprisesamethodoccursbetweenthemethodsopeningand its closing curly brace.Fordisplayingoutputonthescreen, youusethemethodWriteLine()oftheConsoleclass, as shown in line 6. The string passed to the WriteLine() method is displayed onthescreen. Informationthat ispassedtoamethodiscalledanargument. ThelinebeginswithConsole, whichisthenameof apredefinedclassthat supportsconsoleinput/output (I/O). By calling the WriteLine( ) method of the Console class, you displaythe desired output on the screen. You will learn about console I/O in detail in Chapter2, Data Types.NoteC# is a case-sensitive language, and all its statements are terminated with a semicolon. You dont need toterminate the blocks with a semicolon; the blocks are used for grouping statements and begin and endwith two curly braces, { and }, respectively.Line-by-Line Explanation of Code 19Modification of the Main( ) MethodBy default, Visual Studio generates a Main() method that has a void return value and aparameter: an array of string to be used for command-line arguments, as shown here:static void Main(string[] args){}You can always modify theMain() method as per your requirement. You can removetheparameterandchangethereturntypetoint, andsoon. ThefollowingMain()method has no return type and no parameter:static void Main(){}Similarly, the following Main() method returns a value of the int data type:static int Main(){......return 0;}Likewise, the Main() method has a parameter and returns a value of the int data type:static int Main(string[] args){......return 0;}In short, you can use any type of Main() method depending on the programsrequirement.Next, youll quickly write another program. The program shown in Listing 1.4 com-putes the area of a rectangle. The formula is length breadth, and the values of lengthand breadth are given as 50 and 8, respectively.Listing 1.4 Code Written in RectArea.cs Fileusing System;class RectAreaClass{static void Main()20 Chapter 1 n The .NET Framework{int l,b,a;l=50;b=8;a=l*b;Console.WriteLine ( "The area of the rectangle is {0} ", a ) ;}}You can see that three variables, l, b, and a, are defined of int type (integer type). Thevariables l, b, and a are meant for storing the values of the length, breadth, and area ofthe rectangle, respectively. The variables l and b are assigned the given values 50 and 8,respectively. Thecomputedareaoftherectangleisassignedtothevariableaandisthereafter displayed on the screen using theWriteLine() method of theConsole class,as shown in Figure 1.8.NoteThetermintusedinthepreviousexampleisadatatype, andl, b, andaarevariables. Youwill belearning about different data types and variables in the next chapter.Figure 1.8Compiling and running the C# program RectArea.Used with permission from Microsoft.The{0}usedintheWriteLine()methodisaformatspecifierthatisreplacedbythevalueoftheargumentorvariablethatislocatedafterthedoublequotes. Therefore,thevalueof thevariableathat islocatedafterthedoublequotesreplacesthe{0}.Remember, thevalue0incurlybraces{}representsthefirstvariable, 1representsthe second variable, and so on. The following statement makes it clearer:Console.WriteLine ( "Length is {0}, breadth is {1} and the area of the rectangle is {2}",l,b,a ) ;Modification of the Main( ) Method 21Intheprecedingstatement, therearethreevariables, l, b, anda, after thedoublequotes. The value of variable l replaces the format specifier, {0}, the value of b replaces{1}, and the value of variable a replaces {2}, displaying the following output:Length is 50, breadth is 8 and the area of the rectangle is 400WriteLine()methodsupportsconcatenation, ortheadditionofexpressionsbyusingthe + symbol. For example, if youdont like format specifiers, yousubstitute theabove WriteLine() statement by the following:Console.WriteLine ( "Length is " + l +", breadth is "+ b +" and the area of the rectangle is"+a ) ;You can see that the variablesl,b, anda in the preceding statement are used withoutquotes to display their value.SummaryThischapterintroducedC#andthe.NETFramework. Youlearnedabout differentfeatures and components of the .NET Framework, including the CLR, CTS, and CLS.You also came to understand the concept of assembly. You learned about the role ofVisual StudioIDEindevelopingC#applicationsandhowtodownloadandinstallVisual Studio IDE. You also witnessed creating and running the C# programs throughthe Visual Studio IDE as well as through the command-line compiler. Finally, you sawhow to modify the Main() method as per your requirement.The next chapter covers identifiers, keywords, variables, and constants. You will learnabout the two C# predefined data types: predefined value types and predefined refer-ence types. You will also learn about integer, floating-point, decimal, character types,andBooleantypes. Inaddition, youwill readabout stringtypes. Youwill cometounderstandimplicitlytypedvariables, implicitconversion, andexplicittypeconver-sion. Youwill learnabout thepredefinedstreams, consoleI/O, andreadinginputfrom the console. Finally, you will create a Windows Form application step by step.22 Chapter 1 n The .NET FrameworkChapter 2Data TypesThis chapters topics include the following:nIdentifiers and keywordsnVariablesnConstantsnPredefined data typesnPredefined value typesnNullable typesnPredefined reference typesnImplicitly typed variablesnReference typesnBoxingnUnboxingnStreamsnConsole I/OnComment UsenWindows form applicationIdentifiers, keywords, variables, and data types play a major role in programming. Youlearn about them in detail next.23Identifiers and KeywordsIdentifiersarethenamesprogrammersusetorepresent classes, methods, variables,andsoon. For example, intheprogramshowninListing2.1, theidentifiers areSystem, RectAreaClass, Main, l, b, a, Console, and WriteLine.Listing 2.1 Code Written in RectArea.cs Fileusing System;class RectAreaClass{static void Main(){int l,b,a;l=50;b=8;a=l*b;Console.WriteLine ( "The area of the rectangle is {0} ", a ) ;}}AnidentifiermustbeawholewordandshouldbemadeupofUnicodecharacters.Unicodeisacharacter-encodingstandardthat iswidelyacceptedforhandlingandrepresentingtext. Theidentifiers start withaletter oranunderscoreandarecasesensitive.Keywords are names reserved by the compiler that cannot be used as identifiers. Thekeywords in the program shown in Listing 1.4 are using, class, static, void, and int.The full list of C# keywords is shown in Table 2.1.24 Chapter 2 n Data TypesYoushouldavoidusing anidentifier that matches a keyword. But if it is necessary touse anidentifier that matches a keyword, use it withthe @ prefix to avoida collision. For example,the following statement creates a problem because extern is a keyword:int externBut the next statement is correct:int @externThe preceding statements declare extern as an int variable.VariablesVariables, as the name suggests, refer to terms whose values vary. In other words, theykeepavaluethatmightchangeoraremodifiedduringprocessing. Followingisthesyntax for declaring variables in C#:datatype identifier;where datatype can be int, char, and so on.For example:int l;Table 2.1 C# Keywordsabstract as base bool break byte casecatch char checked class const continue decimaldefault delegate do double else enum eventexplicit extern false finally fixed float forforeach goto if implicit in int interfaceinternal is lock long namespace new nullobject operator out override params private protectedpublic readonly ref return sbyte sealed shortsizeof stackalloc static string struct switch thisthrow true try typeof uint ulong uncheckedunsafe ushort using virtual void while 2015 Cengage Learning.Variables 25The preceding statement declares an int variable named l. For safety reasons, you cannotuse this variable in a program until you initialize it. After you declare it, you can assign avalue to the variable using the assignment operator = as shown in the next statement:l = 50;You can declare a variable and initialize it simultaneously:int l = 50;Youcandeclareandinitializemorethanonevariableofthesamedatatypeusingasingle statement:int l = 50, b =8;You can modify the values in the variables l and b while processing.ConstantsAsthenamesuggests, aconstant isavariablewhosevalueisfixedandcannot bechanged. Constants areprefixedwiththe constkeywordandareinitializedat thetime of declaration.For example:const float pi=3.1414F;Because you cannot change the value of a constant, you cannot change pi throughoutthe program.Constants make your programs easier to read and modify. They also help you preventmistakes because the compiler displays an error if you make an attempt to change thevalue of a constant. Remember, you cannot initialize a constant through a variable. Ifyou just change the value of the constant, the changes are automatically applied every-where the constant is used.Predefined Data TypesIn C#, there are two types of predefined data types:nValue typesThese store the value directly. Data types such as int, float, double,bool, and char are value types that are stored on the stack.nReference typesThese data types dont store the value; instead, they store areference to the value. The class objects, strings, and dynamically created variablesare known as reference types because they hold references to blocks of memoryand are managed on the heap. The heap is basically all unallocated memory in anoperating system. When you declare a variable, the compiler allocates a block ofmemory to store a corresponding value.26 Chapter 2 n Data TypesThe following example makes it clearer:int l=50;int b=l;Because the variablel is anint data type, 4 bytes of memory will be allocated for it.The value 50 that is assigned to the variable l is stored in the allocated block of mem-ory. For the variable b, a separate block of 4 bytes of memory is allocated, and its valueof50 is stored in another memory block. The value of50 is stored in two locations inmemory; consequently, the changes made in either variable do not affect the other.For example, if the value of variable l is incremented by 5:l+=5thenonlythememoryblockof variablelisupdatedtoshowthenewvalueof 55.There is no change in the block of memory assigned to variable b.Now considerthe followingexampleof areferencetype. AssumethatRect isaclasswithtwomember variables: length andbreadth. Youwill learnabout classes andobjects in detail in Chapter 7, Classes and Objects.Rect r=new Rect(50,8);Rect s=r;Thevalues50and8areassignedtothemembervariableslengthandbreadthoftheobject r. Remember: only one Rect object, r, is created. r and s point to the same mem-ory location that contains the object. As reference types, the variables r and s just con-tain a reference; that is, they refer to the same object. The value of one object displaysinanother, andthechangesmadeineitherobject affect theother. Becausevalues50and8wereassignedtothemembervariables lengthandbreadth, thefollowingexample displays the value of member variable length (50):Console.WriteLine(s.length);Similarly, after you change the value of the member variable, the length of object s alsomakes the changes in the member variable of object r:s.length=70;Console.WriteLine(r.length);The garbage collector claims the memory allocated to the reference types when therearenoreferencesleftforthem. Similarly, whenthevaluetypesgooutofscope, thememory allocated to themis released. Using value types increases perfor