Anda di halaman 1dari 47

Learning Programming with Microsoft C# - Level 1

Table of Contents
Section: Page:

1.0 .NET CONCEPTS .................................................................................................................................. 2 1.1 .NET BASICS...................................................................................................................... 2 1.2 INTRODUCING THE .NET FRAMEWORK ........................................................................ 4 1.3 UNDERSTANDING THE COMMON TYPE SYSTEM (CTS).............................................. 8 1.4 COMPILERS, ASSEMBLIES, AND MICROSOFT INTERMEDIATE LANGUAGE........... 11 1.5 NAMESPACES ................................................................................................................. 13 2.0 USING WITH THE VISUAL STUDIO .NET IDE ........................................................................... 14 2.1 INTRODUCING THE IDE ................................................................................................. 14 2.2 COMPILING ...................................................................................................................... 19 2.3 DEBUGGING .................................................................................................................... 22 2.4 DATABASE MANIPULATION TOOLS.............................................................................. 27 2.5 GETTING HELP................................................................................................................ 30 3.0 LANGUAGE FUNDAMENTALS ...................................................................................................... 33 3.1 COMMENTS ..................................................................................................................... 33 3.2 TYPES .............................................................................................................................. 34 3.3 CREATING VARIABLES AND CONSTANTS USING VALUE TYPES ............................ 36 3.4 BASIC EXPRESSIONS AND OPERATORS .................................................................... 38 3.5 CASTING AND CONVERSION ........................................................................................ 41 3.6 BUILDING ENUMERATIONS ........................................................................................... 42 3.7 CONTROL OF FLOW ....................................................................................................... 44

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

Learning Programming with Microsoft C# - Level 1

1.0 .NET Concepts


1.1 .NET Basics
When you think about what .NET really is, just look at it as a way of creating Windows applications. It consists of a framework of classes that basically sit on top of the operating system. Each class in the framework provides different functionality, which is exposed by the operating system and other types of system services. .NET also consists of a common type system. In other words, data type usage is totally consistent across all .NET programming languages. This way, no matter what .NET programming language you are using, you will be working with the same underlying data types and data systems. Another nice feature of the .NET programming environment is that a Common Language Runtime is used. You may remember having different types of runtimes depending on which language you were using, or even which version of a language. This problem basically disappears in .NET. In the .NET programming model there is basically one Language Runtime that is used for all languages. This is because every single time that you compile a .NET application it is compiled into a standard format. This standard format is designed to be interpreted, or processed, by the Common Language Runtime mentioned earlier. .NET also exposes a series of high level interfaces that support the ability to create Windows applications and Web-based applications. Think of these as the high level, or application API, that is used to physically create applications, such as Windowing applications or Web services. One of the interesting features provided by the .NET framework is language independence and interoperability. This is actually a very exciting functionality, because this means that no matter which language you use to create your .NET applications, you always end up with the same results. This is different from the idea of a common binary system, such as a .COM compile. You may remember that Visual C++ and earlier version of Visual Basic could all compile .COM objects, and that those .COM objects were basically interoperable. Now, however, you will have access to full-featured language integration. Using .NET you have the ability to handle exceptions across language boundaries. You can also perform debugging across language boundaries,
CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

Learning Programming with Microsoft C# - Level 1 which means that you can debug something in Visual Basic that was created in C#, or vice versa. These elements can be added to your applications in whatever pieces and organizations that you want to. It is all, essentially, interchangeable. Another nice feature of language interoperability is the ability to inherit from objects that are created in the different language. For example, you could create Base Classes in C# and you could still derive from those Base Classes using Visual Basic or another .NET compiling language. This language interoperability gives you the ability to choose a language based on the features and functionality that that language exposes. Another nice feature is interoperability with the Internet. The .NET framework really exposes the Internet very efficiently as one of its underlying services. So, if you are creating Internet applications, or simply network-based applications, the .NET framework gives you the ability to bring standard desktop services together with Internet interoperability. You may recall some of the more complex logic and rules that you had to live by in order to create COM based applications. All of the COM underlying plumbing really goes away in .NET. COM is no longer an issue as far as creating .NET applications goes, because a completely different approach is taken to doing things. You also no longer need to use the Windows registry to register COM interfaces. The Common Language Runtime and lack of COM registration simplifies application deployment. You can have components that have multiple versions running on the same computer. This allows a single server to host multiple versions of the same component because they are not registered in a central register, like the Windows registry. You have the ability to place these objects wherever you want to, and simply have the applications reference the namespaces and elements that you want to use. This is a much more efficient approach when using multiple version of the same object, giving you much more flexibility. Also remember that .NET is based on current communication standards, such as XML, SOAP, and UDDI. You have full implementation of modern, current standards, including network standards, that are supported within the .NET environment.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

Learning Programming with Microsoft C# - Level 1

1.2 Introducing the .NET Framework


In this umbrella that is referred to as the .NET framework, you have a series of different elements and subcomponents. Among these are things such as: .NET Languages Framework Class Libraries Common Language Runtime .NET Binaries (Assemblies)

This list is by no means exhaustive. If you were to put the .NET framework in a hierarchical structure, you would have the Windows operating system at the bottom. Whenever you write an application, the purpose is to provide instructions for the operating system. This means that on top of the operating system you have to have some kind of application runtime. The Common Language Runtime (CLR) for .NET is, basically, an interpreter. You take the application code, which is compiled to an intermediate code, and the CLR is responsible for processing that into machine code that can be run by the operating system. The CLR is made up of a few elements, including the Common Type System, which is the underlying consistent data types, which will be used in every single language. Another part of the CLR is the Common Language Specification. This is the set of rules and requirements that any .NET compiler is required to adhere to. Another way to think of this is as the set of restrictions that make .NET languages what they are. The way you manipulate your data and objects, essentially using the .NET languages, is by using the Framework Class Library, or .NET Base Classes, which would sit on top of the Common Language Runtime in a hierarchical model of the .NET framework. This is the set of classes that expose the basic functionalities that are provided by .NET. These classes include System.Console, which represents the console in the console-based applications, classes that represent the underlying data types, as well as classes that represent Window objects, control objects and web objects. The Framework Class Library is basically composed of abstractions of all of the elements and interfaces that you can use when you build your applications. You manipulate those Framework Class Library elements through your User Interfaces or your Web Service interfaces, which sit on top of the Framework Class Library in the hierarchical model.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

Learning Programming with Microsoft C# - Level 1 Web services are elements and services that are available through the Internet. If you wanted to provide services to an application that you wanted to run in the background and make subscription style services, you could build those using Web service interfaces. You also have User Interfaces such as Win Forms, which are Windows interfaces, and Web Forms, which are your web-based user interfaces. All of these interfaces provide the structure from which you applications may be built. The .NET Languages, which sit at the top of the hierarchical model, are used to manipulate these underlying classes, whether you are talking about specific higher-level services, or the lower level elements of the Framework Class Library. Either way, it is the role and responsibility of the .NET languages to physically manipulate these objects for the creation of your own applications. So basically, what you are doing in your .NET languages is creating your own classes, and the classes that you generate will be implementing and using the services that are provided by the other classes that are in the .NET framework. In its most basic definition you could say that a .NET language is a language that compiles to Microsoft Intermediate Language (MSIL). This is the language that is needed by the Common Language Runtime to physically process and interpret into machine code at runtime on a compile on demand basis. So basically, any language that can give you MSIL is a .NET language. This would include the following official languages, which are released by Microsoft: C# VB.NET Managed extensions to C++ JScript.NET

Windows Forms, or Win Forms, are classes that you use to create applications. All of the classes that you use to represent the Windows themselves, and the controls that you place on the Windows fall into the category of Windows Forms. If you are building desktop style applications, these are what you use. Web Forms are used to create Web-based applications. All of the services that are exposed through ASP.NET, or your web-based interfaces, fall into the category of Web Forms. This includes HTML pages, and all of your various HTML and server controls. Web Services are reusable, backend components that you can plug in to any type of web-based application. In reality it does not even need to be a web-

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

Learning Programming with Microsoft C# - Level 1 based application, as long as these services can be contacted through a network, you can use them in your application structure. A good example of this might be Microsoft Passport. Passport is an authentication services. If you were running an e-commerce website, and wanted to provide some sort of authentication service, you could use Microsoft Passport. Your users would use the Microsoft Passport web service to provide authentication to your website, which saves you the hassle of coming up with your own authentication logic. This is one of the issues that Microsoft really had to keep in mind when they built the .NET model; allowing you to create sets of services, subscription based services that you can plug into your applications, and make the componentization of software more reasonable in a distributed model. The Framework Class Library basically provides for all of the functionality of an application. When you think about the services that are exposed by the operating system, you will be going through the .NET Framework base classes to get access to that functionality. Things that, in the past, you might have used Windows API calls for, or used MSC library calls for, will now be accessed using the Framework base classes. These various class library components include: Data Access GUI Security XML/SOAP IO/Network Threading

This is not a complete list of the services that are exposed by the Base Class library, but is meant to give you an idea of what the Framework Class Library is all about. These services provide all the basic functionality to a .NET language by providing a standard interface for manipulating operating system and services resources. Remember that the Common Language Runtime is the runtime execution engine that is shared by all .NET languages. It does not matter which of them you are coding in; ultimately, your code will be executed by the Common Language Runtime. The CLR is responsible for processing any code that is compiled into the MSIL (Microsoft Intermediate Language) code format. This means that any compiler, that is creating code for the Common Language Runtime must adhere to the
CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

Learning Programming with Microsoft C# - Level 1 Common Language specifications. These specifications state how the code is to be organized, how it will be formed into the MSIL, etc. As far as services are concerned, the CLR is responsible for implementing application runtime services that you might expect for a runtime environment, such as Class Loading, Common Type System, and Garbage Collection. These are all services that you would expect for a modern runtime engine.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

Learning Programming with Microsoft C# - Level 1

1.3 Understanding the Common Type System (CTS)


The Common Type System (CTS) specifies how the types have to be defined in order to run underneath the CLR. There are two general types that the Common Type System supports: Value types and Reference types. The difference between the two is how they are stored in memory. Value types are associated with a specific value itself, where you are really referencing the underlying data. Reference types actually reference an object in memory somewhere, like a pointer. So the Common Type System supports a number of different types, and each of these is used to define different data, whether it is value or reference. Intrinsic, or built in data types, are value types, because they are storing data. There are other types of options, including: Class types Structure types Interface types Enumeration types Delegate types

Technically, every class is a type, in and of itself. These types are introduced, as appropriate, as you proceed through the course.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

Learning Programming with Microsoft C# - Level 1 This chart gives you a little idea of how the underlying type system works for Intrinsic, or built in, data types. .NET defines a series of types, such as bytes and integers, and then each individual language can implement those types using whatever keywords or identifiers that may be relevant and reasonable for their particular language. For example, the System.Byte.NET underlying data type is supported by both VB.NET and C#. The System.SByte, which represents a signed byte data type, is not supported in VB.NET, it does, however, have support implementation in C#. As you can see by the chart, every language is not required to support all of the underlying data types, but they also will not be defining any underlying data types that have not been specifically defined by the .NET framework. This chart also can give you an idea of the types of types that are supported. In addition to those shown, you have floating point data types, both single and double, which are implemented in both VB.NET and C#. There are also data types for: Objects (System.Object) Characters (System.Char) Strings (System.String) Decimals (System.Decimal) Boolean (System.Boolean)

Decimals represent a fixed-point data type, and Boolean represents True and False. The Class Types are pretty basic to developing an application in .NET because they are the reference types that are used to implement all of the structures that are defined by the Class Libraries, whether they are used to reference elements that are part of the underlying foundation classes, or you are defining your own class types. Every single class type defines behaviors of that particular class. The class type members, therefore, consist of things such as: Properties Fields Methods Events

In short, different things that classes do or are.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

Learning Programming with Microsoft C# - Level 1 When you define a class type, you will also be specifying things such as scoping and instantiation specifications, which allows you to indicate where they are visible, how they are instantiated, and whether other classes can be derived from them or not. All of these things are specified when you define you underlying classes. Other CTS types include the Structure types, or Struct. You can think of a structure as a lightweight class. It is based on the System.ValueType base class, so it is not actually a reference type. This means that the data will be stored on the stack, and not on the heap. This means that every instance of the structure type is always going to have its own data, and you will only have one actual reference to that particular type. So, you could not have more than one reference that points to the same physical object when you are using the Structure type. This makes it differ a little bit from the use of classes. The Interface type provides a set of members that you will use to implement into other classes. Interfaces are interesting, because they basically provide a contract. They provide a set of members that you will be using, but they cannot be directly instantiated themselves. They can only be implemented by other objects, other classes. The Enumeration Types define sets of name/value pairs. These are very handy for storing pre-defined property values and method parameters. For example, you could specify that a method would only accept parameters of a certain enumeration type. This allows you to know which values are valid to be passed in to that particular parameter. Delegate Types basically replace the function pointers that you might see in C. They are used to provide forwarding calls and callbacks, essentially pushing data and calls to other functions based on whether or not you need to have one function call back another function, or provide a forwarding call.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

10

Learning Programming with Microsoft C# - Level 1

1.4 Compilers, Assemblies, and Microsoft Intermediate Language


An assembly is nothing more than a binary that is created by a .NET compiler. Planning assemblies takes a little time and effort, but when you plan them correctly, you can control things such as the scope, visibility, and instantiation of their containing classes. The binaries are organized as either an .EXE or a .DLL. No matter which they actually are, the contents of the binary are nothing more than Microsoft Intermediate Language instructions. This means that the assembly creates a completely self-describing meta-data manifest. Conceptually, this is very similar to IDL in COM, except that it is much more verbose and much more complete. So, when you distribute your applications in .NET, what you are actually distributing are your assemblies. Since the assemblies contain Microsoft Intermediate Language (MSIL) this is also an important concept to understand. Remember that the MSIL is really the instructions that are created by the .NET compiler. The .NET compilers that you use must adhere to the Common Language Specifications, which results in the MSIL. All .NET languages basically compile to the same IL. There may be some minor differences, depending on the compiler, in exactly what type of intermediate language you get in terms of how particular tasks are physically completed or executed, but you really end up with basically the same Intermediate Language no matter what compiler you use. The Intermediate Language is processed by the Common Language Runtime. Remember that IL is not machine code. The Common Language Runtime is responsible for doing all of the compile-on-demand of the Intermediate Language. It is the responsibility of the CLR to convert that IL to machine code. In this way, if you are familiar with the Java programming concept, it is very similar to the concept of Java bytecode. The big difference between the IL and Java bytecode is that .NET only targets the Windows platform. With Java bytecode, as long as you have a Java virtual machine that runs on a particular platform, technically the same bytecode could run on any platform. There is, however, no restriction that says that the CLR can only run on Windows. Theoretically it would be possible to create IL compliant Common Language Runtimes that could run on other operating systems. Another interesting distinction between what is happening in the Java world and what is going on with .NET is that bytecode in Java can only be created with the

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

11

Learning Programming with Microsoft C# - Level 1 Java language. There is really only one way to manufacture bytecode, writing Java code and using the Java compiler. With .NET, as you know, there are a number of different .NET languages that you can use. You can pick one, and then use the compiler that is provided for that language to give you the same Intermediate Language result. This gives you more flexibility in implementation, in terms of language and interoperability between languages, than you might get in the Java world.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

12

Learning Programming with Microsoft C# - Level 1

1.5 Namespaces
All of the underlying framework base classes are organized into namespaces. This allows you to get access to them and use them a little more efficiently because of the organization that is provided. Having Namespaces provide all of the organization for class types prevents conflicts between different class types. You can also define your own namespaces when you create your own classes. This means that when you define your own namespaces, you are really providing sets of associated classes. If, for example, you had a class called Account, Account might be used in a number of different ways. If you are implementing Accounts into a receivables type of application, then an Account might behave differently than if you were implementing an account into a payable type of application. In fact, those two Accounts might be entirely different classes, based on the way that they operate. If that is the case, you could actually organize them into two different namespaces. So a Receivables.Account and a Payables.Account represent two distinctly different classes, even though, technically, they have the same name. As you can see, the namespace provides the ability to have multiple different classes using the same name, but not necessarily have a clash, or conflict, between them. In the .NET framework, some of the more common namespaces for the Framework Base Classes include: System System.IO System.Security System.Threading System.Net System.XML System.Windows.Forms

The System namespace is used to define all of the basic system classes. If you remember, all of the basic, built in, types were inside the System namespace. The other namespaces descend from System, and define other specific elements of the underlying system. Everything is logically organized, allowing you to focus on the namespaces that contain the classes that are meaningful to you.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

13

Learning Programming with Microsoft C# - Level 1

2.0 Using with the Visual Studio .NET IDE


2.1 Introducing the IDE
The Visual Studio.NET IDE really is an Integrated Development Environment. It is a unified environment for creating all Microsoft tools-based applications in the .NET framework. So, whether you are creating managed extensions for C++, C# applications, or Visual Basic applications, all of the time you spend learning the IDE is going to be completely transferable to these other environments, because they all use basically the same interface. The IDE contains tools for editing the application code, for handling the compiling, the debugging, data modeling, and deployment. All of these features are available in the IDE. Please note, at the time of this printing, Visual Studio.NET IDE Beta 2 is being used. If you have a later version of the IDE, you may notice a few little differences between what you see here and what you see in your Integrated Development Environment. Assuming that the Visual Studio.NET IDE has already been installed, you can access it through Start, Programs and then going to the Microsoft Visual Studio.NET 7.0 group. Inside this program group you will find the option to run Visual Studio.NET 7.0. When the .NET interface first loads, you will get a start page, which is nothing more than a little web page that gives you some history of projects you have worked on. From this page you can also open existing projects, start new projects, or even access content on the web. You may notice that, surrounding the outside edges of the .NET interface are little icons. These icons can be displayed or hidden through the view menu. Each of the icons represents a window, which will pop out if you hover over the icon that represents it. Moving your mouse away from the window will make it disappear again. These auto-hide windows provide all the basic interface functionality without consuming a lot of real estate on the desktop. Among these windows are: Class View Index Search Solution Explorer Dynamic Help

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

14

Learning Programming with Microsoft C# - Level 1 Class View allows you to look at the actual physical class types that have been created inside any project. The Index is helpful for searching the underlying MSE and help information. Search looks through the documentation. The Solution Explorer, when you have a project open, will list all of the files that are a part of the individual solution. Dynamic Help gives you help specifically tailored to your current situation and what you are doing in the Visual Studio IDE. There is also the Server Explorer, which gives you a tree view of the Servers, Data Servers, and services to which you are currently connected. There is also a Toolbox, which is helpful when working with Win Forms and Web Forms, giving you access to all of the graphical elements and tools that are available. If you cannot see any of these icons on the side of your display, you can enable them through the View menu, as mentioned above. They are directly on the view menu for your convenience.

So, if you want to find one of these windows, and cannot locate it on the desktop, go to the View menu and open it from there. One of the nice features of these auto-hide windows is that you can pin them open if you want to, so they do not disappear when the cursor is moved out of them. This is done by simply clicking the push-pin icon near the X in the upper right corner of any of these windows.

This will not only keep the window you want open, it will make room for it on the desktop, so it is not on top of the main view. When you are done with the
CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

15

Learning Programming with Microsoft C# - Level 1 window, you can have it drop back off the screen by clicking the push-pin icon again, which should be pointing downward while the window is locked open, and it will turn sideways again, as it was before. Now, when you move the cursor away, the auto-hide feature will kick in again and the window will disappear. Another of the nice functionalities that is available in the Visual Studio.NET IDE is an integrated Web browser. At the top of the window, right in the toolbar, are the basics of a Web browser interface.

In the text field you can type in a URL and navigate directly to that URL from within Visual Studio IDE browser. This allows you to look up useful documentation on the web in the same place in which you are doing your programming. There are other features of the Visual Studio.NET interface that you will run into as you start working with Code, but this should give you a general idea of how the Visual Studio.NET interface is organized.

Skill Builder: Creating a Project


Start this Skill Builder with Visual Studio.NET 7.0 installed and running. 1. Click File/New/Project to open the New Project window.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

16

Learning Programming with Microsoft C# - Level 1 The list of Project types that is available depends on the different Visual Studio.NET elements that you have installed. The right hand side of the window will show the different project templates that are supported by the language selected in the left pane of the dialog box. 2. 3. Select Change Console Application from the right pane. The Name of the project to HelloProj. Notice that, under location, you can specify where the project will be stored in the file structure. OK. The IDE creates the Project.

4.

Click

What you will get, be default, since this is a console application, is a class file. The class is automatically titled Class1 with an extension of .cs, which represents a C# class. The code you get should look like this.

You will notice that a namespace is automatically created for you with the name of the Project, as you defined it. This puts the class that you are creating in a namespace with the same name as your project. You will also notice the automatic class name that is assigned, Class1, which is not very descriptive. You may want to change the name of this class to something like SayHello. Remember, however, that you also have a file that has been created that represents the underlying class. If you change the name of the class, it is a good idea to change the name of the file as well.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

17

Learning Programming with Microsoft C# - Level 1

Skill Builder: Changing the File Name


1. 2. 3. 4. Open Rt. Click Select Type The Solution Explorer auto-hide window. Class1.cs in the Explorer. Rename from the popup menu. SayHello.cs for the new name of your class.

This renames the class file in the underlying operating system, and you should see the change to the tab of the working window immediately. At this point you can begin entering the logic you want within the structure of your application. For this example you will be asked to do something fairly simple and print out a message to the console.

Skill Builder: Adding Code


1. Highlight The Following Code. // // TODO: Add code to start application here // Hit Type Delete to remove the code.

2. 3.

The Following Code in the space where the previous code was, one tab to the left of the open and close parenthesis. System.Console.WriteLine(Hello World);

Of course, you have to have a Hello World application in the programming class. Now that you have created your project and defined the logic of the class, you are in a position where you are ready to compile.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

18

Learning Programming with Microsoft C# - Level 1

2.2 Compiling
Remember, the role of the compiler is to take these text files, or source files, and compile them into the Microsoft Intermediate Language. There are two options, you can compile within Visual Studio, or from the command line. When compiling within Visual Studio, you can select Build/Build Solution from the menu, or you can click the Build toolbar button if the Build toolbar is available in your IDE. From the Command line, you can use the command line compiler, csc.exe which stands for C# Compiler. If you were to compile the previous example using this method, the syntax would look like this: C:\>csc SayHello.cs If you are using the command line compiler, there are a number of different switches, or options, you can include. Some of the more common switches include: /? To display compiler options /out To specify name and location for the executable /warnserror Which treats compiler warnings as errors /doc Which processes comments to produce XML documentation

These are not the only compiler options, but they are some of the more common ones. You might want to try the command line compiler with the /? switch to give a current list of the different compiler options you have available. To perform a compile in Visual Studio.NET, you will use the Build process. Selecting Build from the Build menu on the Main Menu bar will accomplish this for the current project. When you have used the build process, you will get a return of information telling you how the build went, including how many builds succeeded, how many failed, and how many were skipped. This appears in a window at the bottom of the screen, and you may notice that this window has a scrollbar, which allows you to view more information than just the succeeded/failed/skipped line. The information in this window tells you the things that happened in process with the build. This is an auto-hide window, so if you move off of the window, and click on your source code, it will disappear. The Output tab remains at the bottom of your workspace, if you have that enabled, and will give you access to that information again if you want it.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

19

Learning Programming with Microsoft C# - Level 1 As with the other auto-hide windows, this one also has a push-pin icon that will let you keep it open while you work elsewhere, if you want to. If you want to do a build using the Build toolbar, you have to have it available. If it is not in your toolbar section you can right click in the toolbar area and select it from the list of toolbar options that pops up. It should be right at the top of the list. Clicking on the Build button has the same effect as selecting Build from the Build menu. If you select a Run operation, a build will take place before the run actually executes. The SayHello.cs file you created a bit earlier is stored as a normal text file. You can see this if you find it through the DOS prompt and use the Edit command to view it. It should appear nearly identical to the code you saw in the IDE. Compiling from the command prompt gives you substantial information back if there is a problem, so if you only get the Compiler version information back, you can feel confident that the compile went smoothly. A command line compile will create the executable for the SayHello.cs file in the same directory, with the same name, but an EXE extension. This contains the Microsoft Intermediate Language that was generated by the compiler. To execute a build from the Visual Studio IDE you can go to the Debug menu.

Here you will see a couple of relevant options, Start and Start Without Debugging. If you select Start, the IDE assumes that you want to invoke the Debugger. Start Without Debugging will allow you to start without going through the Debugger.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

20

Learning Programming with Microsoft C# - Level 1 Try using Start Without Debugging on the SayHello project you created earlier. This will build it, then open a command prompt window showing the text: Hello World Press any key to continue Pressing any key will close the command prompt window and take you back into the Visual Studio IDE. You can perform this same action from the command line as well if you have the executable already compiled. If so, all you need to do is type the name of the executable to run it from the command line.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

21

Learning Programming with Microsoft C# - Level 1

2.3 Debugging
When you are working with Debugging, and are loading a Project to work with, remember to load the Solution file, which represents the project as a whole. When you first open the solution it may not look like anything is open at all. You will need to go to the Solution Explorer and select the part of the project you want to work with, usually a .cs file. When you load a project for debugging you will see the same code display as you saw when working with the project originally. On the right side of the working window there is a gray bar.

Skill Builder: Using the Debugger


1. Create A Class that looks like the following Code.

namespace DebugProj ( class Debug ( static void Main(string[] args) ( for (int i = 0;i<10;i++) ( PrintVal(i); ) ) static void PrintVal(int intVal) ( System.Console.WriteLine(The count is +intVal); ) ) )

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

22

Learning Programming with Microsoft C# - Level 1 This is a simple iteration, using a loop, and the printing of some data every time the loop is run. This particular example will loop through a series of numbers from 0 to 9, and will write each of those values back out to the console. The code itself should not be your focus at this point. It is only there to help illustrate the debugging. 2. Click The Gray area next to the code line that reads: PrintVal(i);

Notice that a reddish dot appears in the gray bar, and the line of code is highlighted in red. This is a Breakpoint, or an instruction to stop the application from processing at that point in the code. 3. Click Debug/Start or hit F5.

This builds the application, starts it, and then stops when the execution reaches the line where you put the Breakpoint. There should be a yellow arrow in the margin where the red dot was, indicating that this will be the next line of code executed if you continue.

This means that the PrintVal statement has not yet run. 4. Hold The Cursor over the PrintVal statement. Notice that a small popup box appears with more information about the statement. You can use this for variables and values as well. The Cursor over the i in the same line to see the value of that variable at this point. It should be zero.

5.

Hold

You should also notice, in the debugger, that a few more windows have popped up as well.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

23

Learning Programming with Microsoft C# - Level 1 In the bottom left corner you have a window with three views, Autos, Locals, and Watch. The Autos view automatically keeps track of a number of different expressions that may be of interest to you. The Locals view gives you the ability to watch all local expressions and arguments. The Watch view allows you to monitor watch expressions that you physically create. If you are interested in watching the value of a variable, or watching the results of a particular expression, you can add the expression to your Watch pane. In the lower right corner there is another window with multiple views.

The first view, the Call Stack, tells you where you are currently executing, and how you got there. If you had called a procedure into another procedure, you might see a lot more information in this window. The Breakpoints tab gives you a list of all the current Breakpoints. The Command Window gives you an interface you can use to actually type code, to interact with your application at this point. The Output Window gives you general CLR output. Feel free to take a look at these views in greater detail. If you wanted to advance to the next line of code in your application after hitting a Breakpoint, there are a number of ways you can do this. There are three buttons on the toolbar specifically related to this, Step Into, Step Over, and Step Out.

The Step Into button, when clicked, will continue through the Code, one line at a time, and any time a procedure is called, it will go through the procedure line by line as well. Also, as you use these buttons, the application is executed, bit-bybit, so if information is to be displayed, once that line is passed, you should be able to see that information in the appropriate place.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

24

Learning Programming with Microsoft C# - Level 1 If you use the Step Over button, if the line you are executing calls another procedure, it will not go through that procedure line by line, but will go through it all as if it were a single line of code. The Step Out button allows you to get out of a procedure that you may have stepped into. This lets you get out of a procedure that you have stepped into, and then realized that you do not need to go through it line by line. All three of these commands are available in the Debug menu, and by the use of keyboard shortcuts. F11 F10 Shift-F11 Step Into Step Over Step Out

Skill Builder: Observing and Manipulating Variables


Start this Skill Builder where the last one left off. You should be in the debugger, stopped at the PrintVal line, and not having stepped into the code at all. 1. Hold The Cursor over the variable (i) in the statement. It should be equal to zero. Step Into until you have returned to the Breakpoint. The Cursor over the variable again. It should equal 1. The Command Window tab on the lower right window. i=5 in the Command Window. The Cursor over the variable again. It should equal 5. Step Into until you have gone through the loop again. The Console Window, where the values are being printed. You should see the following. The count is 0 The count is 5

2. 3.

Click Hold

4.

Click

5. 6.

Type Hold

7. 8.

Click Reveal

This shows you that you do have the ability to manipulate those variable values. You can also manipulate properties, and call methods of a class. You can do

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

25

Learning Programming with Microsoft C# - Level 1 anything you want to within the Command Window as long as it represents a valid action, and the objects that you want to work with are in scope. If you want to set a Watch for the variable, (i), you can do this in a couple of different ways.

Skill Builder: Setting a Watch the Easy Way


1. 2. 3. Hold Rt. Click Select The Cursor over the variable. The Mouse. Add Watch from the list that appears.

When you do this, you should notice that the Watch expression will be added to the Watch window in the lower left hand corner of your screen. This will give you the name of the variable you are watching, its current value, and its data type. If you were to use the Step Into button to advance through the code, you may get errors in the value in the Watch window. This is nothing to worry about. It merely indicates that, at this point in the code, the Watch expression is out of scope. As you continue through the code, it will get back in scope. If you continue with the Step Into function, and get to the incrementation line of code, the value of (i) will change, and the new value will be displayed in red in the Watch window. As you continue to advance it will turn black again, staying at the new value. The red coloring is to highlight the moment of change for a value, helping to call your attention to that point in the code. When you are finished with a Watch, you can delete it by Right Clicking on it, and selecting Delete Watch from the popup menu. Sometimes you may be interested in providing a Watch expression that is a little bit more complex, one in which you cannot just point, click, and choose Add Watch. To do this you can add the Watch expression in the Name category of the Watch list. For instance, if you typed i (without the quotes) in the name column of the Watch list and hit the Enter key, it would add that Watch expression for you. This is how you can add more complex Watch expressions.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

26

Learning Programming with Microsoft C# - Level 1

2.4 Database Manipulation Tools


The IDE has numerous tools that you can use to interact with data sources. What is nice about the data source manipulation options in the IDE is that you can really connect all different types of data sources using OLEDB. Conveniently, any type of local SQL servers are directly accessible in a Window called the Server Explorer. So, if you have SQL servers locally installed, you can go ahead and drill right in to those servers, you can view data, you can edit data, and you can create or modify any objects you want to. If you want to use any other OLEDB compliant data services, you can also use what are called data connections. These allow you to create and OLEDB connection to that service, and also to access and possibly manipulate data through the OLEDB interface. To view existing data, you can start by going to the Server Explorer window. The icon for the Server Explorer is found on the left hand side of the IDE. Server Explorer has two nodes, Data Connections, and Servers. If you expand the Servers, you may see a series of servers, or possibly just the local server that is referenced underneath the Servers node. If you Right Click on Servers you will see that you have the ability to Add a Server to this list. So, if you are trying to monitor another set of services, running on another computer, you can add that server. If you see a server for csharp, and drill into it, you should get a list something like the following.

If you expand the SQL Servers listing you will see the servers you have installed on your computer. If there is a red X as part of the server icon, that means you are not connected to that server. If you hit the Plus sign to expand the server, you will connect to the server and the icon will change.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

27

Learning Programming with Microsoft C# - Level 1 Connecting works the same way with the individual databases, so by the icons you can tell which databases you are connected to, and that connection will be established as soon as you make any inquiry about the database. Within the Server Explorer, if you expand a database you can look at the tables, views, and stored procedures that are contained in that database. If you expand the Tables option you will see all the tables in the database listed.

If you Double Click on one of those tables, you will see the grid for it on the right hand side of the IDE. This is a read-write grid if you are accessing the Visual Studio services by using an identity with the appropriate permissions. Just as you can examine the data for a Table, you can also examine a View or a Stored Procedure. If you examine more than one object tabs will be added to the display on the right, allowing you to quickly go back and revisit previously referenced information. If you have the Visual Studio Enterprise or Architect version installed you will have the ability to create tables, create views, and create stored procedures directly from this interface. If you want to look at other data services you can expand the Data Connections option found at the top of the Server Explorer tree. If nothing comes up, you have no data connections currently installed.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

28

Learning Programming with Microsoft C# - Level 1 If you Right Click on the Data Connections selection and pick Add Connection from the popup menu, you will get the standard Data Link Properties dialog box to work with.

In this dialog box you can set up everything that is necessary to identify a particular OLEDB data service. On the Provider tab you can select and install an OLEDB service provider, and then manage that provider in the Connection, Advanced, and All tabs. This gives you the ability to connect to any OLEDB compliant service by using the data connections node inside the Server Explorer window.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

29

Learning Programming with Microsoft C# - Level 1

2.5 Getting Help


You have quite a few options when seeking help in the Visual Studio environment. One of the more novel approaches is the Dynamic Help model. There is a little window, called Dynamic Help, that will popup different help topics, depending on what you are doing at the time. There is also a traditional help interface, including Contents, Indexes, and Searching. Most of the important help, if it is available, is in the large-scale documentation, such as the Microsoft Developer Network, or MSDN, documentation. This is available in a couple of different ways. You can go out to the website (MSDN.Microsoft.com) where all of the documentation is available. You can also subscribe to MSDN and get regular updates mailed to you on CD or DVD ROM. This subscription comes out quarterly. You can also subscribe to other version of MSDN, such as the Universal Edition, which covers all of the various operating systems and development tools included, or the Professional Edition, which scales down the releases a little bit more. Depending on what type of information and tools you need there is probably an MSDN version that is right for you. The Help is available to you from Slide out windows that you will see on the right side of the IDE. The white question mark in the blue bubble is your Dynamic Help. The blue question mark in the white document icon is the Index. The pink book with the magnifying glass over it is your Search. Again, if you do not see all of these icons on the right side of your screen, you can access them by going to the Main Menu under Help.

Selecting one of these items here, or using the shortcut key combination, will cause the icon to be displayed on the right side of the screen for your use.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

30

Learning Programming with Microsoft C# - Level 1

Skill Builder: Looking at Dynamic Help


Start this Skill Builder with the Start page up for the IDE. 1. Hold The Cursor over the Dynamic Help icon. Notice when the Help window pops out that the contents are geared towards getting started. HelloProj from the project list. You should have created this earlier. Open Project. The Solution Explorer slide out window. SayHello.cs on that list. This should open the code window you worked with earlier. The Cursor over the Dynamic Help icon again.

2.

Select

3. 4. 5.

Click Open Dbl. Clk.

6.

Hold

Notice this time that the help it offers is different from the help options that were displayed when you looked at the beginning of the Skill Builder. Now there are topics on using the Text Editor, Coding Techniques, Using the Debugger, and other specifics related to where you are at the moment. The Getting Started topics are still available. If you open the Index you can look for specific words or phrases, and you can filter your search to certain areas.

If you have already performed searches with the Index you can revisit those searches by clicking the Down arrow next to the Look for field. The Search Window, displayed on the next page, looks like a pretty standard search. If you have used Microsoft Help searches before nothing here should look any different.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

31

Learning Programming with Microsoft C# - Level 1

If you were to type in a topic and click Search, you would get the documentation results for that topic in a separate window, the Output window, which is accessed from the bottom of the screen. The results are listed as topics. If you wanted to see the information in a topic, you would simply double click on it, and that documentation would popup in the main screen. No more than 500 topics will be returned from this type of search. If you are getting the maximum number of results, you can restrict the search to certain areas, or by making the search term more specific. Most of the documentation is pretty standard, and the methods available to search that documentation are also pretty standard. Do not forget that you can use the MSDN library subscription and online sources to get up to the minute help on what is going on in the C# programming environment.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

32

Learning Programming with Microsoft C# - Level 1

3.0 Language Fundamentals


3.1 Comments
One of the things that C# provides to make your life a little bit easier is the ability to provide documentation within the body of your code that can be extracted later, in an XML format. By using three slashes and predefined XML tags, any of the comments you put inside those XML tags are extractable, using the compiler. Here is how that would look inside the code. /// <summary> /// Summary description for Class /// </summary> Remember, when you are using the command line compiler, there is a switch, /doc, that you can use to extract the XML documentation from the source files. The three slash + XML tag approach is how you would identify tags specifically for that documentation. Some of the tags do have pre-defined meanings, so you may want to consult some of the books online to identify the specific sets of tags that you can use, and what those meanings actually are. Another approach for commenting your code is to use the standard line comment. Two forward slashes, followed by text, will be a comment from there until the end of the line. That would look like this: // This is a comment C++ style block comments are also allowed. This uses a forward slash on the outside of the comments, and a star just inside it on either end, like so: /* comment */

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

33

Learning Programming with Microsoft C# - Level 1

3.2 Types
As an example, the intrinsic, or built in data types are actually Value types. A Value type is a type where the data is stored on the stack. The stack is the area of processed memory where the data or call value is stored. The Garbage collection usually occurs when the Stack frame ends. This is usually defined by the function that defines the scope of the call. This means that Value types are designed to be very efficiently stored, and very efficiently destroyed. Objects, on the other hand, are Reference types. Rather than being allocated on the stack, a Reference type is allocated on the heap, so there are references, pointing to those objects, while they sit on the heap. With this in mind, you can have multiple references that refer to the same physical object in the heap. Therefore, when you allocate an object on the heap, a return address is basically allocated to that reference. The Garbage is collected after the last reference to the object has been released. All Value types derive from a single base class, the System.ValueType class. Value types can be the built in, intrinsic data types, such as a float or a character (char), but there may also be user defined Value types, like enum or struct. Because the Value types actually represent elements in a class, they also have properties and methods that are associated with them. Some of the more convenient properties and methods include the GetType method, which can be used to return the type of a particular element. You also have a property called BaseType that you can use to find the base type of any data type. This is very helpful if you want to identify whether or not you are actually dealing with a value type or with a reference type.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

34

Learning Programming with Microsoft C# - Level 1 Following is a list of some of the more common Intrinsic (Value) Types with the number of bytes they take up, and the range of values they might have. byte sbyte bool short (int) ushort char int uint float double decimal long ulong 1 1 1 2 2 2 4 4 4 8 8 8 8 0 to 255 -128 to 127 true or false -32,768 to 32,767 0 to 65,535 Unicode character +/- 2,147,483,64X 0 to 4,294,967,295 single precision float double precision float fixed precision to 28 digits +/- 9,223,372,036,854,775,808 0 to 0xffffffffffffffff (16 fs)

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

35

Learning Programming with Microsoft C# - Level 1

3.3 Creating Variables and Constants Using Value Types


When declaring variables, there will be some basic rules that you have to follow. The variable names must be alphanumeric, or underscore characters. The first character must be alpha or underscore, NOT numeric. No C# Keywords. Use PascalCasing convention for everything but parameters. Make casing exact. Use camelCasing convention for function parameters.

Because C# is case sensitive, you have to stick to a known pattern of casing throughout your applications. To declare the actual variables, you will generally use a format where you declare the data type, and then the variable name. For example: int Myint; This declares that the variable is of the integer data type and that the name of the variable is Myint. You can also initialize the variable when you declare it, like so: int Myint = 5; This declaration creates an integer variable named Myint with an initial value of five. You can also declare multiple variables in one statement by separating them with a comma. int I, J; This statement creates two integer variables with the names I and J. When you need to identify a value that represents a string you enclose those values in double quotes. This is a String value. When you identify characters, you use single quotes. Creating constants is very similar to declaring variables, except you do not have to worry about data type declarations. The primary concern is to identify the name of the constant and then give it a value. You have to assign the value when you create the constant, because when the constant is defined, you cannot change that value. The general convention for creating constants is to use all upper-case characters, although you see different variations on this convention. When you set constants it allows you to use the reference for the constant, instead of reentering the value every time you need it.
CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

36

Learning Programming with Microsoft C# - Level 1 Declaring Reference variables is very much the same as declaring value type variables. The difference, however, is that the variable refers to an object on the heap, rather than the actual variable value itself. Reference type variables will be formally introduced in Level 2 of this course. In this level the focus will be on creating Value type variables. All of the following variable declarations are valid. int X=5; int Y; Y = 6; int I, J; I=10; J=12; When declaring variables, you can see the results of that declaration using the System.Console.WriteLine function. System.Console is a class that supports the WriteLine method. The WriteLine method, when used with the System.Console class, will display information on the command screen. The difference between the Write method and the WriteLine method is that the WriteLine method automatically includes a new line character at the end of its text, whereas the Write method does not.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

37

Learning Programming with Microsoft C# - Level 1

3.4 Basic Expressions and Operators


The C# relational operators are used to give you valid Boolean expressions, so they are used to compare values against other expressions, literals, or values. For example, assume that the value of X is 50. You have a series of operators that you can use to evaluate X in terms of another value. == is the equality comparison operator, so X==50 returns true. != is the Not equal operator, so X!=50 returns false. The standard less than (<), greater than (>), less than or equal to (<=) and greater than or equal to (>=) all function as you would expect. Logical operators are used to build more complex Boolean expressions. You can take multiple Boolean expressions and create larger, broader expressions with them. There are three basic logical operators. &&, & is the AND operator. This is used to check that one Boolean result as well as another Boolean result are both true. The difference between the single ampersand (&) and the double ampersand (&&) is that the double ampersand provides a short circuit evaluation. In other words, if it can determine, by looking at one side of the expression, that the whole thing is false, then it does not bother evaluating the other side of the expression. ||, | is the OR operator, and is used to check that one of the two Boolean results joined by the OR is true, but both need not be. The double vertical line provides the same short circuit evaluation, but in this case if the first part of the expression is true, then the whole expression will be true, and the second part need not be checked. ^ is the Xor operator. The Xor operator is an exclusive OR. This means that one or the other side of the operator may be true, but not both. This means that in all cases, both sides of the expression must be checked. You also have the standard set of mathematical operators available to you. + (addition) - (subtraction) * (multiplication) / (division)

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

38

Learning Programming with Microsoft C# - Level 1 There are also increment operators. ++ (Increment upward by one) -- (Increment downward by one, or decrement)

You can put the Increment operators immediately before or after the variable they are to work on in the code. The difference in results is when the incrementation takes place. For example: Y=X++ If the value of X coming into this expression was five, the value of Y would be set to five, because it is assumes that the value is set before the incrementation takes place. Conversely: Y=++X In this example, if X had a value of five before incrementation, Y would receive a value of six, as the incrementation was performed before the value was assigned. The Decrement operator works the same way. You also have Shift operators available to you, so if you need to do bit shifting there is a right shift and a left shift operator. >> << Shift Right Shift Left

This basically takes the bits in the binary value and shifts those bits whatever number of places you specify. So, 10>>2 would give you 2 as an answer. 10<<2 would give you 40 as an answer. % represents a Mod division operator, which is the remainder of a division. 10%3=1 ?: is a like an immediate IF. This allows you to evaluate an expression, and then perform different actions depending on whether or not the expression is true or false. x==2?x++:y++ If x is equal to 2, increment x, if not, increment y.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

39

Learning Programming with Microsoft C# - Level 1 You also have a series of compound assignment operators available to you. These can be incredibly convenient when you want to add something or subtract something, and then reassign the value into the original operand. A list of the operators and examples of their functions follow. += -+ *= /= x+=5 x-=5 x=5 x/=5 x=x+5 x=x-5 x=x*5 x=x/5

There is a compound assignment for virtually every mathematical operation. If this already looks familiar, that is great. Most of the operators in C# should look familiar based on things you have done before. If some of this is new to you, you may want to go back and review the different operators and their functions. Many of the later operations in this course will depend on an understanding of these operators.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

40

Learning Programming with Microsoft C# - Level 1

3.5 Casting and Conversion


Some data type conversions are going to happen automatically. For example, whenever you convert from a smaller number to a larger number, or you want to save a smaller number into a larger container, this type of conversion will happen automatically. If you wish to explicitly convert from one type to another, and you want a larger object to be saved into a smaller container, then you must explicitly cast. Casting is pretty simple. All you do is take the data type that you want to cast the result into, and put that data type identifier in parenthesis immediately before the value that you wish to cast. Take the following example. intResult = (int)(lngVal1+lngVal2); In this example you assume that you already have a variable called intResult. This will store the value that is created by adding lngVal1 and lngVal2 together. Unfortunately you cannot add two longs together and store them into an integer, because a long plus a long is going to result in a long data type. The only way to accomplish this without error is to cast that result as an int, as shown above. There may be an overflow problem here. That is your responsibility. If you explicitly cast, you are accepting all responsibility that the conversion of the data from one type to another will not result in any type of data corruption.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

41

Learning Programming with Microsoft C# - Level 1

3.6 Building Enumerations


The Enumeration provides a set of pre-defined values for any given type. This is very useful for defining specific sets of values for parameters of a method, or defining a set of valid values for a specific variable instance. Enumerations are actually Value types, so that means that each instance has its own data, and it is basically stored on the stack, the same as any other value. enum JobRole { Administrator, Developer } In the above example an enumerator called JobRole is created, and two valid values are specified for JobRole, Administrator and Developer. No other Job Roles are defined. If you only have two acceptable parameters, it allows you to write if/else statements knowing that if one condition is not met, the only other acceptable condition will be the second one. Here is an example: class EnumClass { static void Main(string[] args) { Respond(JobRole.Developer); } static void Respond(JobRole jr) { if (jr==JobRole.Administrator) { System.Console.WriteLine(Enjoy the network!); } else { System.Console.WriteLine(We love CodeHeads!!); } } } In this example, if the JobRole that is passed in is Administrator, you can write out to the console the string Enjoy the network! but if it is not Administrator, you know that the JobRole must be Developer, and can respond with We love CodeHeads!!
CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1 42

Learning Programming with Microsoft C# - Level 1 If the user tried to pass in something other than a JobRole type, it would fail. If you remove the JobRole from the Respond line, and just pass in Developer, you would get an error. You would be told that the name Developer does not exist in the class, because it has not been defined as anything. If you replaced Developer with an undefined JobRole, such as User, you would also get an error when compiling, because the JobRole enumeration does not contain a definition for the term User. As you can see, you can use the enumeration to properly restrict the values that are acceptable for a parameter of a method, for a variable, or anywhere a value type is needed.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

43

Learning Programming with Microsoft C# - Level 1

3.7 Control of Flow


The Using statement allows you to specify namespaces that you want to implicitly reference within your code. This allows you to avoid using those same namespace references over and over again when you are writing your application. If you do not use the namespace, with the Using statement, it means that you have to explicitly reference any classes you use from that namespace in order to make sure that they can be appropriately identified. For example, up until this point you have been using the Console class, and using the full reference to that class, System.Console. This means if you want to do a WriteLine method on System.Console, you would have to write out the full reference, System.Console.WriteLine(). Alternately, you could use the Using statement and tell it to use System. This implicitly references the System namespace. Basically you are telling the compiler not to whine to you about not finding a particular class until it has searched through all the classes within the referenced namespaces. In short, you are defining a search path. This is how you would code the using of System, and the calling of the WriteLine after that. using System; Console.WriteLine(); You would not get an error with this, because Console is a class within one of the used namespace references. It may not look like you have saved yourself a whole lot of coding just with this example, but if you find yourself using the same class over and over again, or if you find yourself using a set of classes, all within the same namespace, this can be quite convenient. You can have multiple using statements, and use multiple namespaces this way. Generally those using statements will appear at the top of your listing. Another thing you have to concern yourself with when you start creating Controlled Flow processes in your application is the use of Statement Blocks. The curly braces {} are used to identify the beginning and end of statement blocks.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

44

Learning Programming with Microsoft C# - Level 1 The statement blocks, logically, define sets of statements. So, if you use an IF, and have a number of statements you wish to execute if a condition is true, you might include those sets of statements inside a statement block. The statement blocks also assist you in defining things like variable scope, and program flow within the construct of other statements. One of the decision structures that is supported by C# is the IF statement. The IF statement is used to execute code conditionally, based on the value of a Boolean expression. if (Boolean_expression) statement else if(Boolean_expression) statement else { statement statement } In this you will see that there is a Boolean expression in parenthesis immediately after the IF. If that expression is true, you can execute the statement, or statement block, immediately underneath that expression. There is also support for else if blocks if you want to continue to evaluate additional expressions, or else blocks if none of the conditions above match, then the code in the else block will execute. If you have a series of else if structures, over and over again, repeated in an if, you might be better off just using a switch statement. The nice thing about a switch is that it evaluates the expression only once, at the top of the switch. Then it will execute the first matching case that it finds. The structure of the switch is basically an expression at the top, and then a series of cases, that represent valid responses or results or evaluations of that expression. You have probably seen switches before, in C, C++, and Java. The C++ switch behaves pretty much the same, but there is one little difference here. The C++ switch will result in a compile error if it is allowed to fall through from one case to another when that case is not empty. So, if you have a case that has implementation, it is not allowed to fall into the next case. You must provide some sort of mechanism to prevent this fall through.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

45

Learning Programming with Microsoft C# - Level 1 The basic structure of a switch statement looks like this: Switch(X) { case 1: y=1; break; default: y=2; break; } In this example, X is being evaluated. The first case is Case 1, 1 would be the value of that expression. If X=1, then Case 1 will execute, which will assign a value of 1 to the variable, y, and then throw in a break. You have to throw the break in because Case 1 is not an empty case. Without the break, it would fall into the default case, which is not allowed in C#. The Default case provides a case else. Anytime you have no matching cases in the Case structure above, the default case will execute. So, if X equals anything other than 1, you would get an execution of the default case. If you forget to put a break at the end of a non-empty case, it will be caught at the compiler level as an error. The while statement is used for basic iterative processing. What you do is evaluate a Boolean condition at the top of a code block, and a loop will occur as long as the statement evaluates to true. while(i<10) { System.Console.WriteLine(i); i++ } In this example you can see the variable i. As long as i is less than 10, the statement will continue to loop around, repeating over and over. You should also notice that within the executing loop i is incremented, using i++. So, this will loop around until it increments so that i is no longer less than 10. The do statement is also an iterative processing statement, but differs from the while in that with the do statement, the condition is evaluated at the end of the block. The nice thing about the do statement is that you can be sure that the code inside the block will run at least once. With the while statement you have no such assurances.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

46

Learning Programming with Microsoft C# - Level 1 The for statement is useful when you know, or can obtain at runtime, the total number of iterations that you will have to go through in order to run your code effectively. When you create a for statement, you will need to provide three elements to the for structure. Counter variable Boolean condition Increment expression

The Counter variable, if it is defined within the for block, will have scope only for the for block, so you will not be able to use that Counter variable outside of the block. This is usually more of an advantage than a disadvantage. Here is an example of a typical for statement: for (int x=1;x<10;x++) { Console.WriteLine(x); } Console.WriteLine(x); //Error In this case you will notice that in the parenthesis, after the for, an integer variable is declared. (int x=1) This is the Counter variable. The second element in the expression is the condition (x<10). Lastly, there is an incrementation (x++). This means that for every iteration through this loop, the value of x will increase by one. The executed code is a Console.WriteLine to display the value of x. As the value of x increases each time the loop is run, you will see a series of numbers starting with 1 and increasing by one until the loop stops. If, as shown, you decided to try and perform a Console.WriteLine outside of the for block, using that same x variable, it would result in an error, because x only has scope for that block. These different approaches to iterative processing allow you different ways to accomplish the same task, by giving you options in how the task is accomplished. Sometimes these differences can be important to the proper functioning of your application.

CopyrightKeyStone Learning Systems. All Rights Reserved. November 2001. Learning Programming with Microsoft C# - Level 1

47

Anda mungkin juga menyukai