Chapter 2 - 2 Chapter C6374 40569 3:15 PM Page 41 2 Your First C Program In this chapter you will the Distinguish betweenwith different types of

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 2 Chapter C6374 40569 4/6/07 3:15 PM Page 41 2 Your First C# Program In this chapter, you will: the Distinguish betweenwith different types of applications that can be created C# program written Explore athe basic elementsinofC#C# program Examine Learn about installing the .NETaFramework Compile, run, and build an application Debug an application Create an application that displays output Work through a programming example that illustrates the chapter's concepts 2 Chapter C6374 40569 4/6/07 3:15 PM Page 42 42 Chapter 2 Your First C# Program As you learned in Chapter 1, programs are the instructions written to direct a computer to perform a particular task. Each instruction must be written in a specific way.The syntax-- rules for writing these instructions--is defined by the language in which the program is written. Before results are obtained, these human-readable instructions, called source code, must be translated into the machine language, which is the native code of the computer. The translation is a two-step process, which begins with the compiler. In this chapter, you write your first C# program, learn how it is compiled, and explore how the final output is produced. Each instruction statement has a semantic meaning--a specific way in which it should be used. This chapter highlights the purpose of the program statements as they appear in an application, because many of these program elements will be used in all applications that you develop using C#.You'll start by investigating the types of applications that can be developed using C# and the .NET platform. TYPES OF APPLICATIONS DEVELOPED WITH C# C# can be used to create several different types of software applications. Some of the most common applications are: Web applications Windows graphical user interface (GUI) applications Console-based applications In addition to these applications, class libraries and stand-alone components (.dlls), smart device applications, and services can also be created using C#. Web Applications As you remember from Chapter 1, C# was built from the ground up with the Internet in mind. For this reason, programmers can use C# to quickly build applications that run on the Web for end users to view through browser-neutral user interfaces (UIs).As they program in C#, developers can ignore the unique requirements of the platforms--Macintosh,Windows, and Linux--that will be executing these applications and end users will still see consistent results. Using Web forms, which are part of the ASP.NET technology, programmable Web pages can be built that serve as a UI for Web applications. ASP.NET is a programming framework that lets you create applications that run on a Web server and delivers functionality through a browser, such as Microsoft Internet Explorer.Although you can use other languages to create ASP.NET applications, C# takes advantage of the .NET Framework and is generally acknowledged to be the language of choice for ASP.NET development. Much of the .NET Framework class library (FCL) is written in the C# programming language.After you learn some problem-solving techniques and the basic features of the C# language, Chapter 14 introduces you to ASP.NET. Figure 2-1 illustrates an ASP.NET Web page created with C#. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 43 Types of Applications Developed with C# 43 2 Figure 2-1 Web application written using C# Windows Applications Windows applications are designed for desktop use and for a single platform.They run on PC desktops much like your favorite word-processing program.Writing code using C# and classes from the System.Windows.Forms namespace, applications can be developed to include menus, pictures, drop-down controls, and other widgets you have come to expect in a modern desktop application. .NET uses the concept of namespace to group types of similar functionality. The Systems.Windows.Forms namespace is used as an umbrella to organize classes needed to create Windows applications. Using the integrated development environment (IDE) of Visual Studio, GUIs can be developed by dragging and dropping controls such as buttons, text boxes, and labels on the screen.This same drag-and-drop approach is used to create Web applications with Visual Studio.You will begin creating Windows GUI applications in Chapter 8. Figure 2-2 illustrates a Windows application written using the C# language. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 44 44 Chapter 2 Your First C# Program Figure 2-2 Windows application written using C# Console Applications Console applications normally send requests to the operating system to display text on the command console display or to retrieve data from the keyboard. From a beginners' standpoint, console applications are the easiest to create and represent the simplest approach to learning software development, because you do not have to be concerned with the side issues associated with building GUIs.Values can be entered as input with minimal overhead, and output is displayed in a console window, as illustrated in Figure 2-3.You will begin by developing console applications, so that you can focus on the details of programming and problem solving in general. Figure 2-3 Output from Example 2-1 console application 2 Chapter C6374 40569 4/6/07 3:15 PM Page 45 Exploring the First C# Program 45 EXPLORING THE FIRST C# PROGRAM Since the 1970s when the C language was developed, it has been traditional when learning a new language to display "Hello World!" on the console screen as the result of your first program.The program in Example 2-1 demonstrates a C# program that does exactly that.The sections that follow explain line-by-line the elements that make up this first program. 2 Example 2-1 Line1//Thisistraditionallythefirstprogramwritten. Line2usingSystem; Line3namespaceFirstProgram Line4{ Line5classHelloWorld Line6{ Line7staticvoidMain() Line8{ Line9Console.WriteLine("HelloWorld!"); Line10} Line11} Line12} Readability is important. As far as the compiler is concerned, you could actually type the entire program without touching the Enter key.The entire program could be typed as a single line, but it would be very difficult to read and even more challenging to debug.The style in Example 2-1 is a good one to mimic. Notice that curly braces { } are matched and appear on separate lines, by themselves. Statements are grouped together and indented. Indenting is not required, but is a good practice to follow because it makes the code easier to read.When you type your program, you should follow a consistent, similar style.The output produced from compiling and executing the program appears in Figure 2-3. N O T E Formatting code is much simpler with Visual Studio 2005. You can preset your text editor preferences from the Tools, Options menu. You can also purchase plug-ins, such as ReSharper, which do intelligent code editing and formatting for you as you type. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 46 46 Chapter 2 Your First C# Program ELEMENTS OF A C# PROGRAM Although the program statements in Example 2-1 make up one of the smallest functional programs that can be developed using C#, they include all the major components found in most programs.An understanding of the features that make up this program will help prepare you to begin developing your own applications. Examine each segment line-by-line to analyze the program, beginning with Line 1. Comments The first line of Example 2-1 is a comment: Line1//Thisistraditionallythefirstprogramwritten. N O T E Comments are displayed in green throughout the book. Writing a comment is like making notes for yourself or for readers of your program. Comments are not considered instructions to the computer and, therefore, have no effect on the running of the program.When the program is compiled, comments are not checked for rule violations; on the contrary, the compiler ignores and bypasses them. Comments do not have to follow any particular rules--with the exception of how they begin and end. Comments serve two functions: They make the code more readable and they internally document what the program statements are doing.At the beginning of a program, comments are often written to identify who developed the code, when it was developed, and for what purpose the instructions were written. Comments are also used to document the purpose of different sections of code. You can place comments anywhere in the program.Where a portion of the code might be difficult to follow, it is appropriate to place one or more comments explaining the details. In Example 2-1, the only comment is found on Line 1. Line1//Thisistraditionallythefirstprogramwritten. N O T E C# programmers do not normally use line numbers, but they are added here to explain the features. With C#, three types of commenting syntax can be added to a program: inline, multiline, and XML document comments. Inline Comments The comment that appears on Line 1 of Example 2-1 is an inline, or single-line, comment. An inline comment is indicated by two forward slashes // and is usually considered a oneline comment. The slashes indicate that everything to the right of the slashes, on the same line, is a comment and should be ignored by the compiler. No special symbols are needed to end the comment.The carriage return (Enter) ends the comment. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 47 Elements of a C# Program 47 Multiline Comments For longer comments, multiline comments are available.A forward slash followed by an asterisk /* marks the beginning of a multiline comment, and the opposite pattern */ marks the end. Everything that appears between the comment symbols is treated as a comment. Multiline comments are also called block comments. Although they are called multiline comments, they do not have to span more than one line. Unlike the single-line comment that terminates at the end of the current line when the Enter key is pressed, the multiline comment requires special characters /* and */ to begin and terminate the comment, even if the comment just appears on a single line. Example 2-2 shows an example of a multiline comment. 2 Example 2-2 /*Thisisthebeginningofamultiline(block)comment.Itcan goonforseverallinesorjustbeonasingleline.Noadditional symbolsareneededafterthebeginningtwocharacters.Noticethere isnospaceplacedbetweenthetwocharacters.Toendthecomment, usethefollowingsymbols.*/ N O T E C# does not allow you to nest multiline comments. In other words, you cannot place a block comment inside another block comment. The outermost comment is ended at the same time as the inner comment--as soon as the first */ is typed. XML Documentation Comments A third type of comment uses three forward slashes ///.This is an advanced documentation technique used for XML-style comments. XML (Extensible Markup Language) is a markup language that provides a format for describing data using tags similar to HTML tags. A C# compiler reads the XML documentation comments and generates XML documentation from them. You will be using the inline // and multiline /* will develop in this book. */ comments for the applications you Using Directive The following statement that appears in Example 2-1, Line 2 permits the use of classes found in the System namespace without having to qualify them with the word "System".This reduces the amount of typing that would be necessary without the directive. Line2usingSystem; Using .NET provides the significant benefit of making available more than 2000 classes that make up what is called the Framework class library (FCL). A class contains code that can be reused, which makes programming easier and faster because you don't have to reinvent 2 Chapter C6374 40569 4/6/07 3:15 PM Page 48 48 Chapter 2 Your First C# Program the wheel for common types of operations.The Framework classes are all available for use by any of the .NET-supported languages, including C#. N O T E Keywords after they are introduced, such as class, are displayed in blue throughout this book. Keywords are words reserved by the system and have special, predefined meanings. The keyword class, for instance, defines or references a C# class. With several thousand .NET Framework classes, it is very unlikely that program developers will memorize the names of all of the classes, let alone the additional names of members of the classes.As you could well imagine, it would be easy for you to use a name in your own application that has already been used in one or more of the Framework classes. Another likely occurrence is that one or more of these Framework classes could use the same name. How would you know which class was being referenced? .NET eliminates this potential problem by using namespaces. Example 2-3 Assume you have a class called Captain.As discussed in Chapter 1, you could abstract out characteristics and behavior attributes of a Captain. If you had an application that was being developed for a football team, the characteristics and behaviors of that kind of Captain would differ greatly from those of the Captain in an application designed for a fire department. Moreover, both sets of characteristics differ from those of a boating Captain. The Captain associated with a military unit, such as the Navy, would also be different.With each possible application, you could use the same name for the Captain class. If you gave instructions to a program to display information about a Captain, the program would not know which set of characteristics to display. To clarify whether you are talking about the boat Captain, football team Captain, fire station Captain, or the Navy Captain, you could qualify the keyword by preceding the name with its category.To do so, you could write Boat.Captain, Football.Captain, Fireman.Captain, or Navy.Captain.You would need to precede Captain with its category type every time reference was made to Captain. By specifying which namespace you are building an application around, you can eliminate the requirement of preceding Captain with a dot ( . ) and the name of the namespace. If you simply write "use the boating namespace," you do not have to qualify each statement with the prefix name.That is what the using directive accomplishes. It keeps you from having to qualify each class by identifying within which namespace something appears. A using directive enables unqualified use of the types that are members of the namespace. By typing the using-namespace-directive, all the types contained in the given namespace are imported, or available for use within the particular application. The most important and frequently used namespace is System.The System namespace contains classes that define commonly used types or classes.The Console class is defined within the System namespace. The Console class enables programmers to write to 2 Chapter C6374 40569 4/6/07 3:15 PM Page 49 Elements of a C# Program 49 and read from the console window or keyboard. The fully qualified name for Console is System.Console. If you remove the using System; directive in Line 2, it would be necessary for you to replace Line9Console.WriteLine("HelloWorld!"); 2 with Line9System.Console.WriteLine("HelloWorld!"); N O T E In addition to including the using directive, the System namespace must be included in the references for a project created using Visual Studio. When a console application is created, Visual Studio automatically references and imports the System namespace. Namespaces provide scope, or an enclosing context, for the names defined within the group. By including the using directive to indicate the name of the namespace to be used, you can avoid having to precede the class names with the category grouping. After you add the using System; line, you can use the Console class name without explicitly identifying that it is in the System namespace. Namespace Lines 3 through 12 define a namespace called FirstProgram. Line3namespaceFirstProgram Line4{ Line12} The namespace does little more than group semantically related types under a single umbrella. Example 2-1 illustrates how a namespace called FirstProgram is created. FirstProgram is an identifier, simply a user-supplied or user-created name.As noted in the previous section, you will create many names (identifiers) when programming in C#. Rules for creating identifiers are discussed in Chapter 3.You can define your own namespace and indicate that these are names associated with your particular application. Each namespace must be enclosed in curly braces { }. The opening curly brace ( { ) on Line 4 marks the beginning of the FirstProgram namespace.The opening curly brace is matched by a closing curly brace ( } ) at the end of the program on Line 12.Within the curly braces, you write the programming constructs. In the application in Example 2-1, Lines 3, 4, and 12 could have been omitted.This program did not define any new programming constructs or names. It is merely using the Console class, which is part of the System namespace. No errors are introduced by adding the additional umbrella, but it was not necessary. Visual Studio automatically adds a namespace umbrella around applications that are created using the IDE. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 50 50 Chapter 2 Your First C# Program Class Definition Lines 5 through 11 make up the class definition for this application. Line5classHelloWorld Line6{ Line11} As C# is an object-oriented language, everything in C# is designed around a class, which is the building block of an object-oriented program. C# doesn't allow anything to be defined outside of a class. Every program must have at least one class. Classes define a category, or type, of object. Many classes are included with the .NET Framework. Programs written using C# can use these predefined .NET classes or create their own classes. In Example 2-1, the user-defined class is titled HelloWorld.The example also uses the Console class, one of the .NET predefined classes. Every class is named. It is tradition to name the file containing the class the same name as the class name, except the filename will have a .cs extension affixed to the end of the name. C# allows a single file to have more than one class; however, it is common practice to place one user-defined class per file for object-oriented development. N O T E Most object-oriented languages, including Java, restrict a file to one class. C#, however, allows multiple classes to be stored in a single file. Classes are used to define controls such as buttons and labels, as well as types of things such as Student, Captain, and Employee. The word class is a keyword. Like namespaces, each class definition must be enclosed in curly braces { }.The { on Line 6 is an opening curly brace, which marks the beginning of the class definition. The opening curly brace is matched by a closing curly brace at the end of the class definition on Line 11.Within the curly braces, you define the class members. A class member is generally either a member method, which performs some behavior of the class, or a data member, which contains a value associated with the state of the class. Main( ) Method The definition for the Main( ) method begins on Line 7 and ends with the closing curly brace on Line 10. Line7staticvoidMain() Line8{ Line10} The Main( ) method plays a very important role in C#.This is the "entry point" for all applications. This is where the program begins execution. The Main( ) method can be placed anywhere inside the class definition. It begins on Line 7 for this example.When a C# program is launched, the execution starts with the first executable statement found in the Main( ) method and continues to the end of that method. If the application is 3000 lines 2 Chapter C6374 40569 4/6/07 3:15 PM Page 51 Elements of a C# Program 51 long with the Main( ) method beginning on Line 2550, the first statement executed for the application is on Line 2550. N O T E All executable applications must contain a Main( ) method. 2 The entire contents of Line 7 is the heading for the method. A method is a collection of one or more statements combined to perform an action. Methods are similar to C++ functions.The heading for the method contains its signature, which includes the name of the method and its argument list. Return types and modifiers, such as public and static, are part of the heading, but not considered part of the signature.The heading line for the Main( ) method begins with the keyword static, which implies that a single copy of the method is created, and that you can access this method without having an object of the class available. More details regarding static are discussed in subsequent sections. For now, remember that Main( ) should include the static keyword as part of its heading. The second keyword in the heading is void.Void is the return type.Typically, a method calls another method and can return a value to the calling method. Remember that a method is a small block of code that performs an action. As a result of this action, a value might be returned. If a method does not return a value, the void keyword is included to signal that no value is returned.When the method does return a value, the type of value is included as part of the heading. Chapter 3 introduces you to the different data types in C#. Main( ) is the name of the method. Methods communicate with each other by sending arguments inside parentheses or as return values. Sometimes no argument is sent, as is the case when nothing appears inside the parentheses. N O T E Unlike the lowercase main( ) method that appears in the C++ language, in C# Main( ) must begin with an uppercase 'M'. In Example 2-1, only one executable statement is included in the body of the method Main( ). The body includes all items enclosed inside opening and closing curly braces.When a program is executed, the statements that appear in the Main( ) method are executed in sequential order.When the closing curly brace is encountered, the entire program ends. Method Body--Statements The body of this Main( ) method consists of a single, one-line statement found on Line 9. Line8{ Line9Console.WriteLine("HelloWorld!"); Line10} Remember that the purpose of the program in Example 2-1 is to display "Hello World!" on the output screen. The lines of code in Example 2-1, which have been explained on 2 Chapter C6374 40569 4/6/07 3:15 PM Page 52 52 Chapter 2 Your First C# Program previous pages of this chapter, are common to most applications you will be developing. Line 9, however, is unique to this application.The body for this method begins on Line 8 and ends on Line 10. The statement in the Main( ) method is a call to another method named "WriteLine( )". A method call is the same as a method invocation. Like Main( ), WriteLine( ) has a signature.The heading along with the complete body of the method is the definition of the method. When called, WriteLine( ) writes the string argument that appears inside the parentheses to the standard output device, a monitor. After displaying the string, WriteLine( ) advances to the next line, as if the Enter key had been pressed. N O T E A quick way to identify a method is by looking for parentheses--methods always appear with parentheses ( ). A call to any method, such as WriteLine( ), always includes a set of parentheses following the method name identifier, as do signatures for methods. The string of text, "Hello World!", placed inside the parentheses is the method's argument. WriteLine( ) is defined in the Console class and can be called with no arguments.To have a blank line displayed on the standard output device, type: Console.WriteLine();//Nostringargumentisplacedinside() The Console class contains the standard input and output methods for console applications. Methods in this class include Read( ), ReadLine( ), Write(), and WriteLine(). The method Write( ) differs from WriteLine( ) in that it does not automatically advance the carriage return to the next line when it finishes.The following lines would produce the same result as the single line Console.WriteLine("Hello World!"); Console.Write("Hello"); Console.Write(""); Console.WriteLine("World!"); An invisible pointer moves across the output screen as the characters are displayed. As new characters are displayed, it moves to the next position and is ready to print at that location if another output statement is sent. Notice the second statement in the preceding code, Console.Write(" ").This places a blank character between the two words.After displaying the space, the pointer is positioned and ready to display the W in "World." The output for both of the preceding segments of code is: Hello World! Usually, the characters inside the double quotes are displayed exactly as they appear when used as an argument to Write( ) or WriteLine( ). An exception occurs when an escape character is included. The backslash ( '\' ) is called the escape character. The escape character is combined with one or more characters to create a special escape sequence, such as '\n' to represent advance to next line, and '\t' for a tab indention.A number of escape sequences can be used in C#. This is the same set of escape characters 2 Chapter C6374 40569 4/6/07 3:15 PM Page 53 Elements of a C# Program 53 found in other languages such as Java and C++.Table 2-1 lists some of the more commonly used escape characters that can be included as part of a string in C#. Table 2-1 Escape sequences Escape sequence character \n \t \" \' \\ \r \a 2 Description Cursor advances to the next line; similar to pressing the Enter key Cursor advances to the next horizontal tab stop Double quote is printed Single quote is printed Backslash is printed Cursor advances to the beginning of the current line Alert signal (short beep) is sounded When an escape sequence is encountered inside the double quotes, it signals that a special character is to be produced as output.The output of the statement: Console.Write("Whatgoes\nup\nmustcome\tdown."); is Whatgoes up mustcomedown. Notice in the Write( ) method that the argument inside the parentheses has three escape sequences. The backslash is not printed. When the '\n' is encountered, the output is advanced to the new line. The space between the words "come" and "down" was placed there as a result of the tab escape sequence ('\t'). Two other methods in the Console class, Read( ) and ReadLine( ), deserve explanation.Visually they differ from the WriteLine( ) method in that they have no arguments--nothing is placed inside the parentheses. Both the Read( ) and ReadLine( ) methods can return values and are used for accepting input from a standard input device, such as a keyboard. N O T E Notice in Example 2-1 that the statements in the body of methods end in semicolons. But, no semicolon is placed at the end of method headings, class definition headings, or namespace definition headings. Note that semicolons appear on Lines 2 and 9 in Example 2-1. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 54 54 Chapter 2 Your First C# Program Read( ) is often used in a C# program to keep the output screen displayed until the user presses a key on the keyboard.The Read( ) method accepts any character from the input device, and as soon as a key is pressed, control passes to the next line in the program. Instead of accepting a single character as the Read( ) method does, ReadLine( ) allows multiple characters to be entered. It accepts characters until the Enter key is pressed.You will use the ReadLine( ) method in Chapter 4 to input data values. Now that you know what elements make up a C# program, you are almost ready to begin developing your own programs. Figure 2-4 shows how namespace, class, method, and statements are related. Notice that the Framework class library (FCL) includes a number of different namespaces, such as System. Defined within a namespace are a number of classes, such as Console. Defined within a class are a number of methods, such as WriteLine( ) and Read( ).You did not see the statements that made up the WriteLine( ) method, you saw the WriteLine( ) method being called. A method can have one or more statements. One of those statements can be a call to another method, such as the case of calling on the WriteLine( ) method from within the Main( ) method. Framework class library Namespace Class Method Statement Figure 2-4 Relationship among C# elements To develop software using C#, the .NET Framework is needed.The Framework includes all the predefined .NET classes. Having so many classes available decreases the amount of new 2 Chapter C6374 40569 4/6/07 3:15 PM Page 55 Installing the .NET Framework 55 code needed.You can use much of the functionality included in the class library.The next section describes how you get the Framework. INSTALLING THE .NET FRAMEWORK In the previous sections, a working program was examined.To compile, build, and run a C# application, the .NET Framework must be installed. Installation of the Framework places the C# compiler, the common language runtime (CLR), and the predefined classes that make up .NET on your computer. Some installation options include the following: 2 You can download the Microsoft .NET Framework Software Development Kit (SDK) from the Microsoft Web site. It is a free download.At the time of writing, the Uniform Resource Locator (URL) for the downloads was You need to install both the SDK and the Redistributable package to write, build, test, and deploy applications. The Redistributable package needs to be installed prior to installing the SDK. The Redistributable package includes everything you need to run applications developed using the .NET Framework. You will find information about how to download and install these packages at the Microsoft Web site. N O T E After downloading it, double-click the downloaded file and follow the instructions on the screen to finish installing the software on your system.After you complete the installation, be sure to restart your system. These downloads include the extensive library of .NET classes, C# compiler, common language runtime, and everything you need to build, test, and deploy applications. You can download for free Express Editions of the Microsoft .NET languages (C#, J#, C++, and Visual Basic) as well as SQL Server Express and the Visual Web Developer software from the Microsoft Web site.At the time of writing, the URL for Visual C# 2005 Express Edition, which includes a link for the download, was For creating Web applications using an intuitive drag-and-drop user interface, you can download the Microsoft Visual Web Developer Express Edition. It is also free and downloadable at com/vstudio/express/vwd/.The Express line is considered lightweight and lacks the full breadth of features found in the Visual Studio. However, you can use these Express products to write all of the applications illustrated and assigned in this book.The identified Web sites include feature tours, learning resources, and an explanation of the differences between the different product lines. You can purchase the Visual Studio Professional or Team Editions.These are suites of products that include several programming languages, including C#, along with a large collection of development and debugging tools.All of the .NET languages provide access to the Framework, the common execution engine, the large class library, and the capability of creating Web sites and Web services. It is not necessary to download the SDK separately, if you install Visual Studio. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 56 56 Chapter 2 Your First C# Program Several third-party vendors are creating C# compilers. Some of them do not even have to run on a Windows-based platform. On December 13, 2001, the General Assembly of the European Computer Manufacturers Association (ECMA) ratified C# and its Common Language Infrastructure (CLI) specifications into international standards.This opened opportunties for vendors, other than Microsoft, to develop C# compilers. In June 2005, ECMA approved edition 3 of the Common Language Infrastructure (CLI) and C# specifications. If you want to develop on a Linux, MacOS X, or Solaris platform, you might consider downloading Mono or the DotGNU Portable.NET. Both are free implementations. Mono can be downloaded at; DotGNU can be downloaded at Borland Company also markets a C# IDE, which can be downloaded at download_csharpbuilder.html. Of the options listed, the best choice is to use Visual Studio. It is a complete suite of tools for building applications. After you install the software, you need to create a directory to store your applications. Creating a Place to Store Your Work This section explains how to create a directory for your C# programs--preferably on the hard disk of your computer or a shared network drive.To create the directory, either open Windows Explorer or click the My Computer icon on the desktop.To create a storage area, move to the location in which you plan to store your projects. On the File menu, click New, Folder and type a folder name for your projects. For example, suppose you plan to store your work at C:\CSharpProjects. Move to the Local Disk (C:\), open the File menu, click New, Folder, and type CSharpProjects.You should perform this step so that you will have an organized, predetermined location to store your work. Sample projects illustrated in this book are stored in chapter folders inside the CSharpProjects directory. N O T E For your own local personal computer, you should follow these instructions for creating a storage area. However, check with your instructor to determine whether different instructions are needed to set up a place to store your work on campus computers. It might be necessary for you to place your work on secondary storage devices such as flash memory keys. If you do not see the file extension when you browse your files, change the setting to show your file extensions by turning off (deselecting) Hide Extension for known file types. One way to do this is to use the Folder Options in the Control Panel. Using a Windows XP system, click on the Start menu in the lower-left corner of the screen, then click Control Panel, Folder Options, View. Deselect or uncheck Hide extensions for known file types. Select Apply to implement the change. Figure 2-5 illustrates making this change in a Windows XP environment. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 57 Installing the .NET Framework 57 N O T E Depending on the operating system you are using, the wording might be slightly different. For example, in the Windows 2000 operating system, you deselect Hide file extensions for known file types. 2 Figure 2-5 Show file extensions N O T E The file extension includes a dot and two to six characters following the name. Examples are .cs, .csproj, .sys, .doc, .suo, .sln, and .exe. The extension identifies the type of information stored in the file. For example, a file ending in .cs is a C# source file. It is helpful to be able to identify files by type. Typing Your Program Statements You have a couple of options for writing code using C#. One approach to developing applications is to type the source code statements using a simple text editor (such as Notepad) and follow that up by using the DOS command line to compile and execute the application.This technique offers the advantage of not requiring significant system resources. Appendix A, 2 Chapter C6374 40569 4/6/07 3:15 PM Page 58 58 Chapter 2 Your First C# Program "Visual Studio Command-Line Tools," supplies more detail. All that is needed is the downloaded C# compiler with the .NET Framework, Notepad, and access to the DOS command line.This option also offers the opportunity of using the C# programming language on preWindows 2000 operating systems. A second approach is to use the Visual Studio integrated development environment (IDE), and this chapter introduces you to Visual Studio.The IDE is an interactive environment that enables you to type the source code, compile, and execute without leaving the IDE program. Because of the debugging and editing features that are part of the IDE, you will find it much easier to develop applications if Visual Studio is available. In addition to the rich, integrated development environment, Visual Studio includes a number of tools and wizards. To use Visual Studio, you must have at least Windows 2000, XP, or the Vista operating system loaded on a Pentium II-class 600 or higher MHz computer.A processor with a minimum of 1 gigahertz (GHz) is recommended. The RAM recommendations are 256 MB. To install Visual Studio, you need approximately 3.8 GB of available hard disk space for a full install, which includes the MSDN Library.An additional 1 GB of available space is required on the system drive to run the application.Visual Studio does not run under Windows 98 or earlier operating systems. Appendix B, "Visual Studio IDE," describes many additional features of Visual Studio, including suggestions for customizing the IDE. N O T E Windows Vista comes already loaded, by default, with the .NET Framework 3.0. COMPILING, BUILDING, AND RUNNING AN APPLICATION The preceding sections described the program statements required as a minimum in most console-based applications.To see the results of a program, you must type the statements, or source code, into a file, compile that code, and then execute the application.The next sections examine what happens during the compilation and execution process with and without using the Visual Studio IDE. Compilation and Execution Process The compiler is used to check the grammar. It makes sure there are no rule violations in the program statements or source code.After the code is successfully compiled, the compiler usually generates a file that ends with an .exe extension. As noted in Chapter 1, the code in this .exe file has not yet been turned into machine code that is targeted to any specific CPU platform. Instead, the code generated by the compiler is Microsoft Intermediate Language (MSIL), often referred to simply as IL. In the second required step, the just-in-time compiler (JITer) reads the IL code and translates or produces the machine code that runs on the particular platform.After the code is translated in this second step, results can be seen. Operations going on behind the scene are not readily apparent. For example, after the compiler creates the IL, the code can be executed on any machine that has the .NET Framework 2 Chapter C6374 40569 4/6/07 3:15 PM Page 59 Compiling, Building, and Running an Application 59 installed. Microsoft offers as a free distribution the .NET Framework Redistributable version for deploying applications only. The Redistributable version is a smaller download than the SDK and includes the CLR and class libraries.Again, this is available at the Microsoft Web site. The runtime version of the .NET Framework is similar in concept to the Java Virtual Machine (JVM). Like C#, Java's compiler first translates source code into intermediate code called bytecode.The bytecode must be converted to native machine code before results can be seen from an application.With C#, the CLR actually translates only the parts of the program that are being used.This saves time. In addition, after a portion of your IL file has been compiled on a computer, it never needs to be compiled again because the final compiled portion of the program is saved and used the next time that portion of the program is executed. 2 Compiling the Source Code Using Visual Studio IDE You can use the built-in editor available with the Visual Studio IDE to type your program statement.You then compile the source code from one of the pull-down menu options in the IDE and execute the application using another menu option in the IDE. Many shortcuts are available.The next section explores how this is done using the Visual Studio IDE. Begin by opening Visual Studio. Create a new project by either selecting the Create Project button on the Start page or by using the File, New, Project option. As shown in Figure 2-6, a list of project types appears in the left window.The right window contains the templates that can be used within the IDE.To develop a C# console application, select Visual C# Projects as the Project Type and Console Application for the Template. Using the Browse button beside the Location text box, navigate to the location where you want to store your projects.The name of the project is FirstProgram.You can remove the check mark, if it is present, from the check box beside the Create directory for solution option. Having that option selected creates another directory layer. This extra folder is not necessary for the types of applications you will be creating. N O T E Whatever name you give the project becomes the namespace's name for this project unless this default setting is changed. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 60 60 Chapter 2 Your First C# Program Figure 2-6 Creating a console application Selecting the template determines what type of code is generated by the IDE. Figure 2-7 shows the code that is created automatically when you create a console application. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 61 Compiling, Building, and Running an Application 61 2 Figure 2-7 Code automatically generated by Visual Studio As you can see from Figure 2-7, having the IDE generate this much code reduces your typing.The only lines that must be added are those specific to the application being developed. To produce the traditional Hello World program, begin by moving the cursor to the end of Line 10 and pressing the Enter key to open up a new blank line. Type the following line between the braces in the Main( ) method. Console.WriteLine("HelloWorld!"); N O T E Notice that as soon as you type the character C, a smart window listing pops up with Console already selected. This is the Word Correct option of the IntelliSense feature of the IDE. As the name implies, the feature attempts to sense what you are going to type before you type it. When the window pops up, if it has the correct selection, simply type a period and you will get another intelligent pop-up. Again, if it has the correct selection (WriteLine), simply type the next separator, which is the left parenthesis. You can also use the arrow keys to select from the list. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 62 62 Chapter 2 Your First C# Program Next, change the name of the class and the source code filename.Visual Studio names the class Program, and by default identifies the source code file by that same name. If you use the Solution Explorer window to change the source code filename to HelloWorld.cs, a message, as shown in Figure 2-8, will be displayed asking whether you want to change all references to that new name.You can make this change in the Solution Explorer window by either right-clicking on the name in the Solution Explorer window and selecting the Rename option, as is shown in Figure 2-8, or by simply clicking on the name. If the Solution Explorer window is not active on your desktop, select View, Solution Explorer. Be sure to include the .cs file extension when you rename the file. clicking Yes causes the class name to also be renamed Figure 2-8 Changing the source code name from Class1 As you review the Solution Explorer window shown in Figure 2-8, notice the top level reads "Solution `FirstProgram' (1 project)". The second line also contains the word "FirstProject". Visual Studio first creates a solution file. This is the file, FirstProject, which appears on that top line.The solution file may consist of one or more projects. For this application, the solution consists of one project.When you explore the directory where your applications are stored, you will find a folder named using that solution name. Inside the folder there will be a file ending with a .sln extension.This is the solution file and it stores information about the solution. In that same folder, you will also see a file ending with a .csproj extension.This files stores information about the project. Normally when you reopen your application in Visual Studio, you will open the file ending with the .sln extension. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 63 Compiling, Building, and Running an Application 63 If you answer Yes to the question shown in Figure 2-8, the name of the class in the source code is replaced with the new name. N O T E It is not absolutely necessary to change the names of the source code file and class. The application can run without making that change; however, to develop good habits you should change the name. It can save you time and grief when applications involve multiple classes. 2 The statements in Example 2-3 appeared in Example 2-1 and are repeated here without the line numbers so that you can see the final source listing. N O T E Visual Studio generates a couple of other unnecessary lines that can be removed. For example, two of the using statements (Lines 2 and 3) were removed. They are not needed for most of the applications you will develop. The arguments inside the parentheses for the Main( ) method were also removed. You will read about these lines later in this book. Example 2-3 //Thisistraditionallythefirstprogramwritten. usingSystem; namespaceFirstProgram { classHelloWorld { staticvoidMain() { Console.WriteLine("HelloWorld!"); } } } N O T E Do remember that C# is case sensitive, meaning the name HelloWorld is a totally different name from helloWorld, even though only one character is different. So be very careful to type the statements exactly as they are shown. To compile the FirstProgram project, select the Build FirstProgram option on the Build menu, as shown in Figure 2-9.The name FirstProgram follows the Build option because FirstProgram is the name of the project. Projects that contain more than one class are compiled using the Build Solution option. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 64 64 Chapter 2 Your First C# Program N O T E Notice the green vertical lines between the program listing and the line numbers in Figure 2.9. One of the new editor features of Visual Studio 2005 is the Track Changes feature, which shows all changes since the file was opened. Green sidelines highlight changes that were compiled. Yellow sidelines reveal changes yet to be compiled. Changes are reset when the file is reopened. These line revision marks make it easy for you to see which lines have changed during your most recent IDE session. Figure 2-9 Compilation of a project using Visual Studio To run the application, you can click Start Debugging or Start Without Debugging on the Debug menu bar, as illustrated in Figure 2-10. If you attempt to execute code that has not been compiled (using Build), the smart IDE compiles the code first. Therefore, many developers use the shortcut of bypassing the Build step. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 65 Compiling, Building, and Running an Application 65 2 Figure 2-10 Execution of an application using Visual Studio When you ran the application using the Start option, you probably noticed that the output flashes on the screen and then disappears.You can hold the output screen if you include a call to the Read( ) method.When this line is executed, the program waits for you to press a key before it terminates.To add this, go back into the source code and place this line as the last statement in the Main( ) method: Console.Read(); You learned in Chapter 1 that the software development cycle is iterative, and it is sometimes necessary to return to previous phases. Here, it is necessary to return to your source code statements and type the additional statement.You then need to have the code recompiled. When there are no more syntax errors, you will see the output from your program. Another option to hold the command windows in Visual Studio is to select Debug, Start Without Debugging instead of Debug, Start Debugging to execute your program. Notice in Figure 2-10 that Start Without Debugging is the option immediately below the Start Debugging option. If you select Debug, Start Without Debugging, it is not necessary to add the additional Console.Read(); statement.When you use the Start Without Debugging option for execution, the user is prompted to "Press any key to continue," as illustrated in Figure 2-11. This is the preferred method for executing your program. N O T E Several other shortcuts are available to run your program. Notice as you look at the menu option under Debug that Ctrl+F5 is listed as a shortcut for Start Without Debugging; F5 is the shortcut for Start Debugging. In addition, if you have the Debug Toolbars icons on your screen, an open right arrow represents Start Without Debugging. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 66 66 Chapter 2 Your First C# Program Figure 2-11 Output from Hello World Visual Studio is a highly sophisticated integrated development environment. Appendix B, "Visual Studio IDE," includes additional information regarding customizing the development environment and using the debugger for development. Reviewing that material now would be wise. DEBUGGING AN APPLICATION It is inevitable that your programs will not always work properly immediately. Several types of errors can occur and cause you frustration. The major categories of errors--syntax and run-time--are discussed in the next sections. Syntax Errors When you type source code statements into the editor, you are apt to make typing errors by misspelling a name or forgetting to end a statement with a semicolon.These types of errors are categorized as syntax errors and are caught by the compiler. When you compile, the compiler checks the segment of code to see if you have violated any of the rules of the language. If it cannot recognize a statement, it issues an error message, which is sometimes cryptic, but should help you fix the problem. Error messages in Visual Studio are more descriptive than those issued at the command line. But, be aware that a single typing error can generate several error messages. Figure 2-12 shows a segment of code, in which a single error causes the compiler to generate three error messages. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 67 Debugging an Application 67 Missing ending double quote 2 Pushpin Errors reported Figure 2-12 Syntax error message listing The error messages are displayed in the Error List window found at the bottom of the IDE. The IDE also underlines the supposed location of the problem.You can also double-click on any of the error messages to go directly to the line flagged by the compiler. If the Error List tab is not visible on your screen, you can select Error List from the View menu. A pushpin icon appears in the upper-right corner of all tool windows such as that shown in the Error List window.When the pushpin stands up like a thumbtack, the window is docked in place; thus, the Error List window is docked in place in Figure 2-12. N O T E Tool windows support a feature called Auto Hide. If you click the pushpin so that it appears to be lying on its side, the window minimizes along the edges of the IDE. A small tab with the window name appears along the edge. This frees up space so you can see more of your source code. The syntax error shown in Figure 2-12 is a common mistake.The double quote was omitted from the end of the argument to the WriteLine( ) method at Line 9.The error message does not say that, however.When you are reviewing error messages, keep in mind that the message might not be issued until the compiler reaches the next line or next block of code. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 68 68 Chapter 2 Your First C# Program Look for the problem in the general area that is flagged. Some of the most common errors are failing to end an opening curly brace ( { ) or having an extra closing curly brace ( } ), failing to type a semicolon at the end of a statement (;), and misspelling names.As a good exercise, consider purposefully omitting curly braces, semicolons, and misspelling words. See what kind of error messages each mistake generates.You will then be more equipped to find those errors quickly when you develop more sophisticated applications in the future. N O T E Because one error can generate several messages, it is probably best to fix the first error and then recompile rather than trying to fix all the errors in one pass. Run-time Errors Run-time errors are much more difficult to detect than syntax errors.A program containing run-time errors might compile without any problems, run, and produce results. Run-time errors can also cause a program to crash.A program might be written to retrieve data from a file. If that file is not available, when the program runs, a run-time error occurs.Another type of run-time error is division by zero. Many times, a program compiles and executes without errors, but does not perform as expected. If the results are incorrect, the associated error is called a logic error. Logic errors are not identified until you look closely at the results and verify their correctness. For example, a value might not be calculated correctly.The wrong formula might be used. Failing to understand the problem specification fully is the most common culprit in logic errors. It is not enough to produce output; the output must be a correct solution to the problem. Another potential run-time error type will be introduced when you start working with data in Chapter 3. If you are using data for calculations or performing different steps based on the value of data, it is easy to encounter a run-time error. Run-time errors can be minimized during software development by performing a thorough analysis and design before beginning the coding phase.The common strategy of desk checking, introduced in Chapter 1, also leads to more accurate results. CREATING AN APPLICATION Now that you understand what is required in most C# programs and how to compile and see your results, work through the following example using the suggested methodology for program development introduced in Chapter 1. In this section, you design a solution for the following problem definition. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 69 Programming Example: ProgrammingMessage 69 PROGRAMMING EXAMPLE: PROGRAMMINGMESSAGE The problem specification is shown in Figure 2-13. 2 Figure 2-13 Problem specification sheet for the ProgrammingMessage example Analyze the Problem Do you understand the problem definition? This step is often slighted or glossed over. It is easy to scan the problem definition and think you have a handle on the problem, but miss an important feature. If you do not devote adequate time and energy analyzing the problem definition, much time and expense might be wasted in later steps.This is one, if not the most important, step in the development process.Ask questions to clarify the problem definition if necessary.You want to make sure you fully grasp what is expected. As you read the problem definition given in Figure 2-13, note that no program inputs are required.The only data needed for this application is a string of characters.This greatly simplifies the analysis phase. The desired output, as noted in the problem specification sheet in Figure 2-13, is to display "Programming can be FUN!" on two lines. For this example, as well as any other application you develop, it is helpful to determine what your final output should look like. One way to document your desired output is to construct a prototype, or mock-up, of the output. Prototypes range from being elaborate designs created with graphics, word-processing, or paint programs, to being quite cryptic sketches created with paper and pencil. It is crucial to realize the importance of constructing a prototype, no matter which method you use. Developing a prototype helps Design a Solution 2 Chapter C6374 40569 4/6/07 3:15 PM Page 70 70 Chapter 2 Your First C# Program you construct your algorithm. Prototypes also provide additional documentation detailing the purpose of the application. Figure 2-14 shows a prototype of the final output for the ProgrammingMessage example. Figure 2-14 Prototype for the ProgrammingMessage example During design, it is important to develop an algorithm.The algorithm for this problem could be developed using a flowchart.The algorithm should include a step-bystep solution for solving the problem, which, in this case, is straightforward and involves merely the output of a string of characters. Figure 2-15 contains a flowchart defining the steps needed for the ProgrammingMessage example. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 71 Programming Example: ProgrammingMessage 71 2 Figure 2-15 Algorithm for ProgrammingMessage example Another option is to use structured English or pseudocode to define the algorithm.The pseudocode for this problem would be very short. It would include a single line to display the message "Programming can be FUN!" on the output screen. Using an object-oriented approach to design, the solutions normally entail creating class diagrams. No data members would need to be defined for this problem.The Console class in the System namespace already has methods you can use to display output on a standard output device.Thus, no new methods or behaviors would need to be defined. So, if you were to construct a class diagram, it would include only a heading for the class. Nothing would appear in the middle or bottom portion of the diagram. Because the diagram does not provide additional documentation or help with the design of this simple problem, it is not drawn. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 72 72 Chapter 2 Your First C# Program As noted in Chapter 1, after the algorithm is developed, the design should be checked for correctness. One way to do this is to desk check your algorithms by mimicking the computer and working through the code step-by-step as if you were the computer. When you step through the flowchart, it should produce the output that appears on the prototype. It is extremely important that you carefully design and check your algorithm for correctness before beginning to write your code.You will spend much less time and experience much less frustration if you do this. Code the Solution After you have completed the design and verified the algorithm's correctness, it is time to translate the design into source code. You can type source code statements into the computer using a simple editor such as Notepad, or you can create the file usingVisual Studio. In this step of the process, you must pay attention to the language syntax rules. If you create the application usingVisual Studio, the IDE automatically generates much of the code for you. Some of that code can be removed or disregarded. For example, did you notice that the two using statements (using System.Text; and using System.Collections.Generic;) were removed in the previous example? You can again remove or disregard these clauses.The using System; is the only using clause that needs to remain with your program statements for most of the applications that you will be developing. Visual Studio also modifies the Main( ) method's heading from what you saw previously in this chapter.The signature for Main( ) can have an empty argument list or include "string[ ] args" inside the parentheses. For the types of applications you are developing, you do not need to send the additional argument. So, you can also disregard or completely remove the argument inside the parentheses to Main( ) at this time. You might want to change the name of the source code file, and allow Visual Studio to change all references to that name. When you typed ProgrammingMessage as the project name, the IDE automatically named the namespace ProgrammingMessage. The class could also be called ProgrammingMessage, and this would cause no name clashing problems such as the namespace being given the same name as the class name. Figure 2-16 illustrates the changes you might want to make to the code generated by Visual Studio. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 73 Programming Example: ProgrammingMessage 73 May want to remove all the XML comments (lines beginning with ///) Change the name Delete [STAThread] Can replace with static void Main() 2 Replace TODO: with your program statements Figure 2-16 Recommended deletions The only lines that you had to type were found in the Main( ) body. Console.WriteLine("Programmingcanbe"); Console.WriteLine("FUN!"); Console.Read(); The final program listing looks like this: /*Programmer:[supplyyourname] Date:[supplythecurrentdate] Purpose:Thisclasscanbeusedtosendmessages totheoutputscreen. */ usingSystem; namespaceProgrammingMessage { classProgrammingMessage { staticvoidMain() 2 Chapter C6374 40569 4/6/07 3:15 PM Page 74 74 Chapter 2 Your First C# Program { Console.WriteLine("Programmingcanbe"); Console.WriteLine("FUN!"); Console.Read(); } } } At the beginning of your program, identify the author of the code, and as a minimum specify the purpose of the project. Note that the statements inside the Main( ) method are executed in sequential order.The Read( ) method is executed after the two WriteLine( ) methods. Read( ) is used in a program to keep the output screen displayed until the user presses a key.After a character is pressed on the keyboard, control passes to the next line that marks the end of the application. Implement the Code During implementation, the source code is compiled to check for rule violations.To compile from within the Visual Studio IDE, use the Build menu option. If you have errors, they must be corrected before you can go forward. From within the Visual Studio IDE, select Start Without Debugging on the Debug menu bar to see the results. Test and Debug Just because you have no compiler syntax errors and receive output does not mean the results are correct. During this final step, test the program and ensure you have the correct result.The output should match your prototype. Is your spacing correct? By following the steps outlined in this chapter, you have officially become a C# programmer.The program you created was a simple one. However, the concepts you learned in this chapter are essential to your progress. In Chapter 3, you begin working with data. Resources As noted in Chapter 1, there are enormous numbers of sites devoted to C# on the Web. Here are a few more interesting and useful sites: Borland C# download at DotGNU Portable.NET C# free download at portable_net.html Microsoft Visual Web Developer Express Edition at express/vwd Microsoft Visual C# 2005 Express Edition at visualcsharp/ Microsoft .NET Framework Software Development Kit (SDK) at downloads 2 Chapter C6374 40569 4/6/07 3:15 PM Page 75 Quick Review 75 Mono C# free download at ReSharper at Visual C# Learning Resources -- Absolute Beginners Video Series at com/vstudio/express/visualcsharp/learning/default.aspx#beginners 2 QUICK REVIEW 1. C# can be used to create Web,Windows, and console applications. 2. Web pages are created using Web forms, which are part of the ASP.NET technology. 3. Windows applications are considered desktop bound and designed for a single platform. 4. Console applications are the easiest to create.Values can be entered and produced with 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. minimal overhead. C# programs usually begin with a comment or using directives, followed by an optional namespace grouping and then the required class definition. All C# programs must define a class. Comments are written as notes to yourself or to readers of your program.The compiler ignores comments. It is not necessary to end single inline comments //; they end when the Enter key is pressed. Comments that span more than one line should be enclosed between /* */. These are considered block or multiline comments. Over 2000 classes make up the Framework class library.A class contains data members and methods or behaviors that can be reused. The using-namespace-directive imports all the types contained in the given namespace. By specifying the namespace around which you are building an application, you can eliminate the need of preceding a class with a dot ( . ) and the name of the namespace. Everything in C# is designed around a class. Every program must have at least one class. A method is a collection of one or more statements taken together that perform an action. In other words, a method is a small block of code that performs an action. The Main( ) method is the "entry point" for every C# console application. It is the point at which execution begins. The keyword static indicates that a single copy of the method is created. The keyword void is included to signal that no value is returned.The complete signature of a method starts with the return type, followed by the name of the method, and finally a parenthesized list of arguments. One signature for Main( ) is void static Main( ). 2 Chapter C6374 40569 4/6/07 3:15 PM Page 76 76 Chapter 2 Your First C# Program 16. WriteLine( ) writes a string message to the monitor or a standard output device. 17. Methods communicate with each other through arguments placed inside parentheses. 18. Readability is important. Indenting is not required, but it is a good practice because it 19. 20. 21. 22. makes the code easier to read. To see the results of a program, you must type the statements (source code) into a file, compile that code, and then execute the application. Visual Studio integrated development environment (IDE) is an interactive development environment that enables you to type the source code, compile, and execute without leaving the IDE program. One way to document your desired output is to construct a prototype, or mock-up, of your output. The Read( ) method accepts any character from a standard input device, such as a keyboard. It does nothing with the character. EXERCISES 1. ASP.NET creates which type of application? a. Windows b. console c. command d. Web e. services 2. Which beginning symbol(s) identifies the following 10 lines as comments? a. /* b. ** c. // d. /// e. */ 3. System is an example of a(n): a. object b. class c. method d. namespace e. directive 2 Chapter C6374 40569 4/6/07 3:15 PM Page 77 Exercises 77 4. A(n) groups semantically related types under a single name. 5. 6. 7. 8. a. object b. class c. method d. namespace e. directive To mark the beginning and end of a block of code, C# programmers use: a. [ ] b. { } c. ( ) d. begin... end e. start... stop Which of the following is a keyword? a. Main( ) b. System c. using d. WriteLine e. all of the above Which of the following is a signature for a method? a. Main( ) b. Console.WriteLine("Ok"); c. using Programming1 d. static System.Read( ) e. none of the above The fully qualified call to the method that allows the user to input a single character is: a. Console.System.Read( ) b. System.Console.Read( ) c. Console.System.Write( ) d. System.Console.Write( ) e. System.Console.ReadLine( ) 2 2 Chapter C6374 40569 4/6/07 3:15 PM Page 78 78 Chapter 2 Your First C# Program 9. Source code must be translated into machine code (also called native code).This two- 10. 11. 12. 13. step process begins with a(n): a. debugger b. editor c. interpreter d. JITer e. compiler A(n) is a mock-up of desired output. a. prototype b. algorithm c. diagram d. specification e. none of the above What is the name of the feature in Visual Studio that displays in a scrollable list all available methods and properties when the dot is typed after an object name? a. Help b. Rotor c. Mono d. IntelliSense e. ToolTip To see the results of an application, you the code. a. compile b. JIT c. execute d. edit e. desk check A console application is characterized by: a. containing a Main( ) class b. containing a Main( ) method c. featuring a GUI d. belonging to the Web Forms class e. requiring the use of a System.Interface namespace 2 Chapter C6374 40569 4/6/07 3:15 PM Page 79 Exercises 79 14. Which escape sequence can be used to indicate the cursor should advance to the next line? a. newline b. escape next c. \n d. \newline e. \r 15. Which of the following is a call to a method? a. Console.Write; b. Console.Write["ok"]; c. Write.Console("ok"); d. Console.Write("ok"); e. none of the above 16. Identify one syntax error that might occur when you type Example 2-1 into an editor. 2 Identify one logic error that might occur. 17. What is produced when you run the following application? Line1//Exampleprogramdisplayingoutput. Line2usingSystem; Line3namespaceExerciseI Line4{ Line5classProblem2 Line6{ Line7staticvoidMain() Line8{ Line9Console.Write("Go"); Line10Console.Write("Laugh"); Line11Console.WriteLine("OutLoud"); Line12Console.Write("Think"); Line13Console.Write("Happy"); Line14} Line15} Line16} 18. What must be changed in the segment of code in Exercise #17 to cause all of the out- put to be displayed on one line? 19. Search the Internet and identify the URL of one site, other than Microsoft, that has a C# compiler available for download. 2 Chapter C6374 40569 4/6/07 3:15 PM Page 80 80 Chapter 2 Your First C# Program 20. Using the program segment in Exercise #17, identify line number(s) in which each of the following can be found: a. method invocation b. namespace c. class name d. argument to a method e. comment f. identifier 21. Identify the syntax error(s) (if any) in the following: Line1usingSystem Line2namesspaceExerciseI Line3{ Line4Problem2 Line5{ Line6staticMain() Line7{ Line8console.write("ok") Line9} Line10} Line11} 22. Explain the relationship between System, Console, and Read. 23. Think algorithmically.Write a set of instructions for each of the following activities. Your algorithm should be so complete that you could give it to other people, and they could perform the task specified without asking additional questions. a. Make a peanut butter and jelly sandwich. b. Walk to your next class. c. Purchase a bottle of water from a vending machine. PROGRAMMING EXERCISES 1. Write a program that produces the following output. Replace the name Tyler Howard with your name. Hello,Tyler Howard 2 Chapter C6374 40569 4/6/07 3:15 PM Page 81 Programming Exercises 81 2. First develop a prototype, and then write a program that displays the name of the pro- gramming language discussed in this text. One possible design is given here. CCCCCCCCCC CC ## ## CC ############## CC ## ## CC ############## CC ## ## CCCCCCCCCC 3. Hangman is a favorite childhood game. Design the stick figure for this game and produce a printed listing with your stickman. One possible design follows.You may implement this design or develop an improved version. (^;^) | ./ | \. | _/ \_ 4. Every program that you create should begin with internal documentation identifying the assignment.You might want to include some of these items: programming assignment number, your name as developer, program due date, the date the program is turned in, and the purpose of the application. Develop an application that produces a banner containing this information.Your output might look similar to the following: *********************************************** *ProgrammingAssignment#4* *Developer:AlmaKing* *DateSubmitted:September17* *Purpose:Provideinternaldocumentation.* *********************************************** 2 In addition to printing the output screen banner shown in the preceding code segment, be sure to include appropriate comments as internal documentation to your program. 5. Flags are a symbol of unity and invoke special meaning to their followers. Create a design for a flag, and write a program that displays your design. One possible design follows. *******---------------------------------*******---------------------------------*******---------------------------------*******-------------------------------------------------------------------------------------------------------------------------- 2 Chapter C6374 40569 4/6/07 3:15 PM Page 82 82 Chapter 2 Your First C# Program 6. Create an application that produces the following output. It should be displayed on 7. 8. 9. 10. three lines, exactly as it appears here. Today is the FIRST day of the rest of your life. Live it to the FULLEST! You may not get a second chance... Exercise 6 presents a popular saying. Produce a listing containing your favorite saying. Double space the output and print the saying one word per line. Print your birth year in one column. For example, if you were born in 1982, your output should look like the following: 1 9 8 2 Create an application that displays the following patterns.You may use any character of your choice to construct the pattern. ********* * * ********* *** *** ********* ****** ***** ********* ******** ******* ********* ********** ********* ********* ************ ******* ********* ************** ***** ********* **************** *** ********* ****************** * Write your initials in block characters to a standard output device. Design your prototype using the symbol(s) of your choice. ...
View Full Document

This note was uploaded on 09/09/2008 for the course CS 158 taught by Professor Doyle during the Fall '07 term at Jacksonville University.

Ask a homework question - tutors are online