Thursday, July 8, 2010

Tuesday, July 6, 2010

ENUMERATIONS

Enums Defined

Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast.

Enums lend themselves to more maintainable code because they are symbolic, allowing you to work with integral values, but using a meaningful name to do so. For example, what type of code would you rather work with - a set of values named North, South, East, and West or the set of integers 0, 1, 2, and 3 that mapped to the same values, respectively? Enums make working with strongly typed constants via symbolic names easy.

Enums are value types, which means they contain their own value, can't inherit or be inherited from, and assignment copies the value of one enum to another. You will see in this lesson and elsewhere that enums are used and referred to with both lower case, enum, and upper case, Enum. The relationship between the two is that the C# type, enum, inherits the Base Class Library (BCL) type, Enum. Use the C# type, enum, to define new enums and use the BCL type, Enum, to implement static enum methods.


Creating an Enum


Creating an Enum

The .NET Framework Class Library contains many enums and examples of how they are used. For example, every time you put an icon on a MessageBox, you use the MessageBoxIcon enum. For a list of available enums in the .NET Framework Class Library, look at the documentation for the Enum class and click on the Derived Classes link.

Whenever there are situations where you are using a set of related numbers in a program, consider replacing those numbers with enums. It will make a program more readable and type safe. Listing 17-1 contains an enum definition and code that uses that enum in a switch statement. Instead of using the numbers 0, 1, and 2 in the switch statement, the code is more meaningful through the use of the Volume enum.

The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example:

      enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initializers to override the default values. For example:

      enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

In this enumeration, the sequence of elements is forced to start from 1 instead of 0.

A variable of type Days can be assigned any value in the range of the underlying type; the values are not limited to the named constants.

The default value of an enum E is the value produced by the expression (E)0.

NoteNote

An enumerator may not contain white space in its name.

The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is needed to convert from enum type to an integral type. For example, the following statement assigns the enumerator Sun to a variable of the type int using a cast to convert from enum to int:

int x = (int)Days.Sun;
When you apply System.FlagsAttribute to an enumeration that contains some elements combined with a bitwise OR operation, you will notice that the attribute affects the behavior of the enum when used with some tools. You can notice these changes when using tools such as the Console class methods, the Expression Evaluator, and so forth.


Example

In this example, an enumeration, Days, is declared. Two enumerators are explicitly converted to integer and assigned to integer variables.

// keyword_enum.cs
// enum initialization:
using System;
public class EnumTest
{
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

static void Main()
{
int x = (int)Days.Sun;
int y = (int)Days.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}

Output

Sun = 2
Fri = 7

In this example, the base-type option is used to declare an enum whose members are of the type long. Notice that even though the underlying type of the enumeration is long, the enumeration members must still be explicitly converted to type long using a cast.

// keyword_enum2.cs
// Using long enumerators
using System;
public class EnumTest
{
enum Range :long {Max = 2147483648L, Min = 255L};
static void Main()
{
long x = (long)Range.Max;
long y = (long)Range.Min;
Console.WriteLine("Max = {0}", x);
Console.WriteLine("Min = {0}", y);
}
}

Output

Max = 2147483648
Min = 255

The following code example illustrates the use and effect of the System.FlagsAttribute attribute on an enum declaration.

// enumFlags.cs
// Using the FlagsAttribute on enumerations.
using System;

[Flags]
public enum CarOptions
{
SunRoof = 0x01,
Spoiler = 0x02,
FogLights = 0x04,
TintedWindows = 0x08,
}

class FlagTest
{
static void Main()
{
CarOptions options = CarOptions.SunRoof | CarOptions.FogLights;
Console.WriteLine(options);
Console.WriteLine((int)options);
}
}

Output

SunRoof, FogLights
5

Friday, July 2, 2010

Introduction

C#, pronounced c sharp, is a computer language used to give instructions that tell the Computer what to do, how to do it, and when to do it. This is a universal language that is used on many Operating Systems, including Microsoft Windows. C# is one of the languages used in the Microsoft .NET Framework. The Microsoft .NET Framework is a library of objects that create or draw things on the computer.

Console Applications

The C# language is used to create that display on a black window referred to as the DOS prompt or DOS window. Those are the types of applications we will create in our lessons.

To study the C# language, we will use Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional. To get Microsoft Visual C# 2008 Express Edition, you can download it free from the Microsoft web site. After downloading it, you can install it.

To launch Microsoft Visual C# 2008 Express Edition, you can click Start -> (All) Programs -> Microsoft Visual C# 2008 Expression Edition:


Microsoft Visual C# 2005 Expression Edition

To launch Microsoft Visual C# 2008 Professional, you can click Start -> (All) Programs -> Microsoft Visual Studio 2008. To create the type of applications we will study in our lessons, on the main menu, you can click File -> New Project... In the Templates section of the New Project dialog box, you can click Console Application, accept the default name or change it:

New Project

After clicking OK, a skeleton code would be created for you. Right now, we will not review every part of the code. Everything will be introduced and explained as we move on.

Writing Code


Introduction


The programs we will write are meant to give instructions to the computer about what to do, when to do something, and how to do it. You write these instructions in an easy to understand English format, using words we will study. This means that a regular instruction uses normal text with alphabetic characters, numbers, and non-readable symbols. Normally, you can write your instructions using any text editor such as Notepad, WordPad, WordPerfect, or Microsoft Word, etc. When writing your instructions, there are rules your must follow and suggestions you should observe. We sill study each one of them as we move on.

The group of instructions used by your program is also referred to as code. To assist you with writing code, Microsoft Visual C# 2008 includes a text editor referred to as the Code Editor. This is the window that displays when you have just created a console application. Besides the Code Editor, the integrated development interface (IDE) of the Microsoft Visual C# 2008 is made of various parts, which we will review when necessary.

Practical Learning: Creating a Program


  1. Start Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional
  2. To create a new application, on the Start Page, on the right side of Create, click Project
  3. In the Templates section, click Console Application
  4. Change the Name to GeorgetownCleaningServices1 and click OK

Comments


A comment is a line or paragraph of text that will not be considered as part of your code of a program. There are two types of comments recognized by C#.

To display a comment on a line of text, start the line with two forward slashes //. Anything on the right side of // would be ignored. Here is an example:

// This line will be ignored. I can write in it anything I want

The above type of comment is used on only one line. You can also start a comment with /*. This type of comment ends with */. Anything between this combination of /* and */ would not be read. Therefore, you can use this technique to span a comment on more than one line.

Practical Learning: Creating Comments


  1. To create comments, change the file as follows:
    using System;
    // using System.Collections.Generic;
    // using System.Linq;
    // using System.Text;
    /*
    namespace GeorgetownCleaningServices1
    {*/
    class Program
    {
    static void Main(/* string[] args */)
    {
    }
    }
    //}
  2. To save the project, on the Standard toolbar, click the Save All button

    Save Project
  3. Accept the name as GeorgetownCleaningServices1 and click Save

Code Colors


Code is written in a wide area with a white background. This is the area you use the keyboard to insert code with common readable characters. The Code Editor uses some colors to differentiate categories of words or lines of text. The colors used are highly customizable. To change the colors, on the main menu, you can click Tools -> Options... In the Options dialog box, in the Environment section, click Fonts and Colors. To set the color of a category, in the Display Items section, click the category. In the Item Foreground combo box, select the desired color. If you want the words of the category to have a colored background, click the arrow of the Item Background combo box and select one:

In both cases, the combo boxes display a fixed list of colors. If you want more colors, you can click a Custom button to display the Color dialog box that allows you to "create" a color.

Indentation


Indentation is another feature that makes your program easy to read. Indentation is a technique of grouping lines of code by category. To delimit the items of your code, you should indent them by two empty spaces or one tab. Indentation should be incremental. That is, when a line of code appears to be a child of the previous line, the new line should be indented.


Solution and Project Management


A Project


We have seen how to create a console application. Microsoft Visual C# allows you to create various other types of applications. This is why you should first display the New Project dialog box to select your option. Besides console applications, in future lessons, we will start some applications with the Empty Project. We will also learn how to create a library using the Class Library option. We will ignore the other three options in this book.

To control the indentation of your code, on the main menu, click Tools -> Options... In the left list, expand C#, followed by Formatting and click Indentation. Then change the options on the right side:

Indentation

After making the changes, click OK to validate or Cancel to ignore.

Saving a Project


In previous versions of Microsoft Visual C# (namely 2002 and 2003), you always had to formally create a project in order to use one and you always had to save it. After realizing that many of the projects that developers or students create are for experimental purposes, Microsoft provided the ability to only temporarily create a project, then to save it or not. Saving a project allows you to keep on a medium so you can refer to it later.

When Microsoft Visual Studio 2008 (any edition) is installed, it creates a folder named Visual Studio 2008 in your My Documents folder. The My Documents folder is called your personal drive or your personal directory. Inside of the Visual Studio 2008 folder, it creates a sub-folder named Projects. By default, this is where it would save your projects, each with its own folder.

To save a project, on the Standard toolbar, you can click the Save All button . Alternatively, on the main menu, you can click File -> Save All. If the project had already been saved but you want to save it under a different name, on the main menu, you can click File -> Save project name As...

A Solution


A solution is used to coordinate the different aspects of an application that is being created. When you create a project, it represents one detail of the application you have in mind. Besides the code you are writing, you may want to add other items. Instead of one project, in the next sections, we will see that a solution can contain more than one project.

When creating a project, the solution holds the same name as the project. You can see their names in the Solution Explorer:

Solution Explorer

The solution and a project can have different names. While working on a project, to rename the solution, in the Solution Explorer, you can click the first node, which is the name of the solution starting with Solution. Then, in the Properties window, click (Name) and type the name of your choice:

Solution Explorer

This name is temporary, especially if you have not yet saved the project. If you want to permanently save a solution for later use, there are two techniques you can use.

If you start saving a project for the first time, it would bring the Save Project dialog box. By default, Microsoft Visual Studio selects your personal directory as the path to the solution. This is called the location. In the location, Microsoft Visual Studio creates a folder as the solution of the project. The solution must have, or must be stored, in its own folder. As mentioned earlier, Microsoft Visual Studio uses the name of the project as the name of the solution. To rename the solution, you can change the string in the Solution Name text box. Remember that you can enter the name of the project in the Name text box. Here is an example:

Save Project

When you save a project (for the first time), by default, Microsoft Visual C# creates a new folder for it in the My Documents\Visual Studio 2008\Projects folder. It uses the name of the solution to name the folder. It creates some files and stores them in that new folder. Then, it creates a sub-folder, using the name of the project, inside of the folder of the solution. Besides the sub-folder with the name as the project, it creates another folder named debug. It also creates another folder named Debug in the sub-folder of the name of the project. In each folder and some other folders, it creates some files that we will not pay attention to for now.

If the project had already been saved but you want to change the name of the solution, on the main menu, you can click File -> Save solution-name.sln As... This would bring the Save File As dialog box where you can specify the name of the solution and click Save.

Executing a Project


After creating a project and writing code, you may want to see the result. To do this, you must execute the application. This would create an executable that you can use on other computers and that you can distribute to other people.

To execute an application, on the main menu, you can click Debug -> Start Without Debugging. Instead of going through the main menu every time, you can add the Start Without Debugging button to a toolbar. To do this, you can right-click any toolbar and click Customize... In the Commands property page of the Customize dialog box, you can click Debug in the Categories click, then drag Start Without Debugging, and drop it on a toolbar. Here is an example:

Integrated Development Environment

After adding the button(s), you can click Close. The next time you want to execute an application, you can just click this button.

Practical LearningPractical Learning: Executing an Application


  1. To execute the application, on the main menu, click Debug -> Start Without Debugging
  2. After viewing the result in a DOS window, press Enter to close it

Adding a Project


One of the most valuable features of Microsoft Visual Studio 2005 is that it allows you to work on more than one project without launching more than one instance of the studio. This means that you can add a project to another project you are working on and treat each as a separate entity.

Before adding one project to another, you must save, or you must have saved, the current project. To add a project, in the Solution Explorer, you can right-click the most top node (it starts with Solution) and position the mouse on Add:

Solution Explorer

If you have a project that was previously saved but you don't want to open a separate instance of Microsoft Visual Studio for it, you can click Existing Project... This would bring the Add Existing Project dialog box that allows you to select a project from a folder.

To add a new project, after right-clicking, you can click New Project... If you add a new project, and if you want to keep it for future references, you must save it. To save the new project, you can click the Save All button on the Standard toolbar. After saving the new project, a folder with its name would be created inside of the folder of the solution.

On the right side of the name of the solution in Solution, the number of its projects is specified in parentheses, as 1 project, or 2 projects, etc.

After adding a project, each would be represented by its own node in the Solution Explorer and in the Class View. Here is an example:

Solution Explorer

Also, a sub-folder for each project is created in the folder of the solution:

Windows Explorer

In the Solution, the name of one of the projects, if there is more than one, is in bold characters. This project is called the StartUp Project. If, on the main menu, you click Debug -> Start Without Debugging, the project in bold characters would be executed. If you want to change the start up project, you can right-click its node and click Set As StartUp Project.