Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2.0 With CSharp (2006) [eng]

.pdf
Скачиваний:
86
Добавлен:
16.08.2013
Размер:
20.33 Mб
Скачать

Chapter 9

What Are All Those Curly Brackets and Semicolons For?

These are covered in more detail later in the chapter, but you’ll see a brief explanation now so you understand what you are seeing. The first thing to note is that in C#, a line of code only ends when the semicolon character (;) is reached. This means that you can spread the code line across multiple physical lines to make it easier to read, or so it doesn’t scroll off the end of the window.

The next thing to know is that the code blocks are surrounded by curly brackets ({}), which define the start and end of the code block. There will be lots more on these later in the chapter, explaining when these are required, but for now just know that they are part of the language. The term curly brackets is often used to differentiate them from parentheses of square brackets.

The other really important thing to know about C# is that it is case-sensitive. In Visual Basic .NET it doesn’t matter what case you use, and IntelliSense will correct the language keywords. In C#, however, what you type is what you get, so a common cause of errors is simply mistyping — you know, when you mistakenly hit the Caps Lock key instead of the Shift or Tab key.

Declaring Variables

There is a specific syntax for creating variables, which requires the data type and name. The name is up to you, but it’s always best to use a sensible name, something that represents what the variable holds. To define a variable you use the data type followed by the variable name, like so:

DataType VariableName;

Replace the VariableName and DataType with your requirements:

string FirstName; string LastName;

int Age;

DateTime Birthday;

Here you see sensible names for the variables: there are two string types to hold the first and last names, an int to hold the age, and a DateTime to hold the birthday. In some documents and books, you might see a prefix on the variable name, giving an indication of its data type. For example, the names and ages might be declared like so:

string strFirstName; string sLastName;

int iAge;

DateTime dBirthday;

Here str or s has been used as a prefix for string types, i for int types, and d for DateTime data types. You may find this technique useful when learning how to use variables and data types, although it isn’t generally recommended and has dropped out of favor. A correctly named variable should give a good indication of its data type. Having said that, there are times when some form of prefix is useful, and you’ll see this when you look at classes later in the chapter.

288

Code

Assigning Values

After you declare a variable, you can assign values to it, and this is simply a matter of setting the variable equal to the required value. The syntax for this is as follows:

variable = value;

This says give the variable named on the left of the equals sign the value on the right of the equals sign. For example:

FirstName = “Arthur”;

LastName = “Arbuthnot”;

Age = 24;

As you can see, string values are enclosed in quotation marks, whereas numeric values aren’t.

Variables can also be initialized when they are declared, like so:

string FirstName = “Arthur”; string LastName = “Arbuthnot”;

int Age = 24;

DateTime Birthday = new DateTime(1980, 22, 10);

These examples show the assignment using literal values, but you can also assign values to other variables or objects. For example, in ASP.NET pages, it’s very common to assign values from user-entered data, perhaps from a text box:

FirstName = FirstNameTextBox.Text;

LastName = LastNameTextBox.Text;

Or vice versa:

FirstNameTextBox.Text = FirstName;

LastNameTextBox.Text = LastName;

The TextBox control has a property called Text that contains the text value, so you are simply copying that value into the string variable, or copying the string value into the property. This is fine for string types, but extra work needs to be done if the variable isn’t a string type. For example, allowing a user to enter his age would require a text box and an int type variable. However, you can’t assign the values of differing types — you need to convert them.

Data Conversion

Visual Basic .NET provides some automatic conversion of data types, but C# doesn’t provide this facility, and you have to explicitly convert variables between data types. Explicit conversion makes it clear exactly what your code does, a useful point when you (or others) look at your code later. There isn’t a single syntax for converting between types, but there is a lot of commonality in the different methods.

289

Chapter 9

Converting to string values is the simplest, because every data type has a ToString method. For example, to convert age to a TextBox you could use the following:

AgeTextBox.Text = Age.ToString();

For the bool type the conversion method is the same, but the string value will be either true or false.

Converting from a string value to another type is slightly different, because there aren’t methods on the string type to do this automatically. Instead you have to use a separate class to perform the conversion.

Converting Data Types Using the Framework Classes

There are two ways to convert from string values to other types using the framework classes, and it’s worth mentioning both in case you see them in code. The first is to use the Parse method that most data types supply. For example, to convert a number held in a TextBox control into an int data type, you could do this:

int Age;

Age = int.Parse(AgeTextBox.Text);

What’s happening here is that the Parse method parses the value passed to it — that is, it reads the value, checks that it is an integer value, and converts it into an integer. The value to be converted is the value from the Text property of the AgeTextBox control, which is a string. So the string is passed into the Parse method, which converts it into an integer and returns the integer, which in turn is assigned to the Age variable.

All of the data types, apart from Object, support the Parse method, which means that even though you may be using a different data type, the syntax is the same. For example:

double ANumber;

ANumber = Double.Parse(NumberTextBox.Text);

The second way to perform data conversion is to use the Convert class, which converts between types. It’s a very flexible class because it can convert between all types, but it requires knowledge of the CLR type. For example, the preceding example using an integer could be written as follows:

int Age;

Age = Convert.ToInt32(AgeTextBox.Text);

For the double example, this would be:

double ANumber;

ANumber = Convert.ToDouble(NumberTextBox.Text);

In use there is no difference between the Convert class and the data type class when converting types. The only reason for using the Convert class is that it makes code easier to convert to another language. This was important when writing the Wrox United web site, but may not be important to you if you intend to stick with one language.

290

Code

Converting Data Types with Casting

Another way of converting between types is by casting. Instead of explicitly converting the type, the value is forced into another type. Casting doesn’t work in the same way as converting, and isn’t always suitable. For example, you can’t use casting to convert from strings to numbers. You can, however, use casting to convert between similar types. For example, you could cast between a double and an int by using the following code:

double MyDouble = 123.456; int MyInteger;

MyInteger = (int)MyDouble;

The last line in this code example shows the actual cast — the use of the data type surrounded by parentheses — the (int) bit. This tells the compiler to take the value of the MyDouble variable and convert it to an integer type, which has the effect of just removing all of the digits after the decimal point. It doesn’t change the MyDouble variable at all — that is still a double and still retains the original value.

One thing you should be aware of is that casting may change the value of the variable. In the preceding example this is obvious, because changing a floating-point number into an integer will lose the values after the decimal point. Converting between a long and an int isn’t so obvious, but may result in changes. Because an int has a range half that of a long, if the value in the long exceeds that of the integer, the value will be shortened when converted.

Explicit Conversion

You may see another form of conversion, but not realize it’s actually a conversion:

float num = 18.3f;

This follows the usual form of declaration but has an f on the end. The reason for this is that 18.3 is taken as a double, so you would get a compiler error saying that a double cannot be implicitly converted to a float. Adding the f to the end of 18.3 does an explicit conversion.

Null Values

All data types have default values, but there is also the concept of a null value. This doesn’t usually affect the standard types, and is more common on custom or complex types. It simply means that the object doesn’t exist. For example, consider a method that returns a DataSet object, filled with data from a database. What happens if, while fetching the data, there is some sort of error? There will probably be an exception thrown (these are covered in Chapter 15), but the method still might return, only there’s no data for you — the value returned might be null.

In C# the null value is represented by the keyword null. You look at how you test for null values later.

Working with Strings

When working with strings, it’s useful to know that the string class has a great number of methods that allow you to manipulate those strings, and any variable that is a string therefore has the ability to use those methods. You won’t go into all of them here, instead concentrating on some of the most common ones.

291

Chapter 9

One of the most common requirements is being able to strip blank spaces (or white space as it’s sometimes called) from the beginning or end of strings. This is useful when taking input from a user and is especially important when trying to compare two string values. For example, consider the following code fragment:

string

Name1

=

“Dave”;

 

string

Name2

=

“Dave

“;

if (Name1 == Name2)

The if test would result in false, because the strings aren’t the same — Name2 has spaces at the end. Three methods can help here: TrimStart removes spaces from the start of the string, TrimEnd removes spaces from the end of a string, and Trim removes spaces from both the start and end of a string. If the preceding code were modified to include Trim, the result would be true:

string

Name1

=

“Dave”;

 

string

Name2

=

“Dave

“;

if (Name1.Trim() == Name2.Trim())

Both strings have been trimmed, so the if test would return true. The strings have only been trimmed as part of the comparison, though; the strings haven’t been modified themselves. Consider this code:

string

Name1

=

“Dave”;

 

string

Name2

=

“Dave

“;

if (Name1.Trim() == Name2.Trim())

{

// this would return true

}

if (Name1 == Name2)

{

// this would return False

}

You can see that using Trim only affects that one instance, unless the underlying variable is changed:

string

Name1

=

“Dave”;

 

string

Name2

=

“Dave

“;

Name1 = Name1.Trim();

Name2 = Name2.Trim();

if (Name1 == Name2)

{

// this would return True

}

Now that Name1 and Name2 have been reassigned with the trimmed values, subsequent comparisons work. The key point here is that using string methods only affects that particular use of the string, and the string variable will only be changed if assignment is done.

292

Code

Another situation that can occur when comparing strings, especially those supplied by user input, is mismatched case. What if the user has the Caps Lock key on? Two methods help with this: ToLower, which converts the string to lowercase, and ToUpper, which converts the string to uppercase. For example:

string Name1 = “dave”; string Name2 = “DAVE”;

if (Name1 == Name2)

This code would fail because the strings are different, even though we know them to mean the same thing. To get around this, you can change the case:

string Name1 = “dave”; string Name2 = “DAVE”;

if (Name1.ToLower() == Name2.ToLower())

Now the test would succeed because the values being compared are lowercase.

Plenty of other string methods exist, some of which are described here:

EndsWith returns true if the string ends with a given string. For example:

if (MyString.EndsWith(“ate”))

StartsWith returns true if the string starts with a given string. For example:

if (MyString.StartsWith(“wha”))

IndexOf returns the position within the string of a given character or string, or -1 if the item isn’t found. For example:

if (MyString.IndexOf(“abc”) > 0)

Insert inserts a string at a given position. For example, to insert the string new words at position 5 you would use this:

MyString.Insert(5, “new words”);

LastIndexOf returns the last position within the string of a given character or string. This is similar to IndexOf but is useful for finding the last instance of a character.

PadLeft and PadRight perform the opposite of Trim, allowing you to pad strings to a given length. The padding defaults to a space but can be any character. For example, to pad a string to a total of 15 characters, you would use the following:

MyNewString = MyString.PadLeft(15)

Remove removes a section of a string. For example, to remove five characters starting at position 4, you would use this:

MyNewString = MyString.Remove(4, 5);

293

Chapter 9

Replace replaces characters within the string. For example, to replace abc with def you would use this:

MyNewString = MyString.Replace(“abc”, “def”)

SubString returns a portion of a string. For example, to return five characters starting at position 4, you would use this:

MyNewString = MyString.SubString(4, 5);

For a full list of string methods, you should consult the documentation. The String type has a couple of properties, but the only one you will probably use is Length, which returns the number of characters within the string.

Working with Dates

In C#, you can place dates as literals into your code, but one problem with this is that it has to be in the MM/DD/YYYY format, which can be confusing if you are in a country that doesn’t use that format. For example, take the date 03/05/2005 — does this represent March 5 or May 3? You could easily assume the format, but that leads to potential errors.

Instead of using literals to initialize dates, C# uses the DateTime object to create a new instance on a date, like so:

DateTime Birthday = new DateTime(2005, 3, 5);

The parameters are in year, month, and day order, and because you have IntelliSense (or at least the documentation if you aren’t using VWD), you know what the order should be. If required, the individual parts of the date can be accessed like so:

int day = Birthday.Day; int month = Birthday.Month; int year = Birthday.Year;

There are other properties such as DayOfWeek and DayOfYear, as well as ones for dealing with the time and parts of the time. You can find more information about these additional properties in the documentation.

Dates behave just like numeric variables in that they allow addition, subtraction, and comparison. For example, you can add a number of days using the AddDays method:

NewDate = Birthday.AddDays(18);

There is also a Subtract method that subtracts one date from another. However, this method doesn’t return a Date type, but rather a TimeSpan, which is a data type used to define spans of time. For example:

DateTime Date1 = new Date(2005, 3, 10);

DateTime Date2 = new Date(2005, 3, 5);

TimeSpan Difference;

Difference = Date1.Subtract(Date2);

Label1.Text = Difference.ToString();

294

Code

This code creates two dates, March 10 and March 5, and then declares a variable of type TimeSpan, which will hold the difference between the dates. The difference is calculated by using the Subtract method of the date — because the Date1 variable is a Date type the Subtract method can be used, and Date2 is passed into this method. The result is that Date2 is subtracted from Date1, and in this case the result would be 5.00:00:00, which represents 5 days, 0 hours, 0 seconds, and 0 milliseconds.

Now that you have a good base of knowledge to work with, the following Try It Out has you work with simple data types.

Try It Out

Working with Simple Types

1.Open the directory for the Chapter 9 samples, called Chapter09 and located under the directory where you placed the sample code.

2.Create a new Web Form called SimpleTypes.aspx. Remember to make sure it uses a separate file for the code.

3.Drag three text boxes, three labels, and a button onto the page, so it looks like Figure 9-1. Make sure the TextBox and Label controls are in order, so TextBox1 is at the top, followed by

TextBox2, and then TextBox3.

Figure 9-1

4.Double-click the button to create the code-behind file and button click event, and add the following code into the event procedure:

Label1.Text = TextBox1.Text + TextBox2.Text;

Label2.Text = DateTime.Parse(TextBox3.Text).ToString(“dd MMM yyyy”); Label3.Text = DateTime.Parse(TextBox3.Text).ToString();

5.Save both the Web Form and the code-behind file, and set the Web Form to be the start page (right-click the page in the Solution Explorer).

6.Press F5 to run the page and enter 3 into the first text box, enter 4 into the second text box, and enter 12/2/05 into the third text box.

7.Press the button and observe the results. On a machine configured with UK regional settings, you’ll see Figure 9-2.

295

Chapter 9

Figure 9-2

With the regional settings set to USA, Figure 9-3 will appear.

Figure 9-3

How It Works

There are two points to note about this page. The first is that the numbers you entered into the text boxes haven’t been added as you might expect, and the second is that the date format changes depending upon the regional settings.

Take a look at the numbers first:

Label1.Text = TextBox1.Text + TextBox2.Text;

The code seems obvious, just adding two numbers, but you have to remember that the Text property of the TextBox control returns a string. For strings, the addition operator (+) means concatenation, so it simply joins the strings. To add the strings, you would have to convert them to numbers first, like so:

Label1.Text = Convert.ToInt32(TextBox1.Text) + Convert.ToInt32(TextBox.Text);

Here the Convert class is used to convert the text to numbers, so when the addition is done, the values are numbers.

296

Code

For the dates, you have to consider the regional settings of the machine that the web server is running on — this is where the code is executed. As it happens, when running the VWD web server, the machine processing the pages is the same as your browser, but on a real web site, this isn’t the case. So take a look at what the code does. The first line converts the value from the text box into a DateTime type by using the Parse method, and then it converts it back into a string. The ToString method has an explicit format, where dd is the day number, MMM is the month name, and yyyy is the year:

Label2.Text = DateTime.Parse(TextBox3.Text).ToString(“dd MMM yyyy”);

The reason for converting to a date and back to a string is to show that parsing the date is systemdependent. So if you are writing a web site for a company that uses a different date format from yours, the results you see may not always be what you expect.

The final line of code shows what the default ToString method does:

Label3.Text = DateTime.Parse(TextBox3.Text).ToString();

This simply shows the date and time. Notice that this displays the same value for the date regardless of the regional settings. The time is shown differently but again that’s because of the regional settings on the machine. You might like to experiment with your regional settings to see how the output differs. If you do this, you will need to stop the VWD web server before rerunning the application; you can do this by selecting the icon in the task tray and clicking Stop from the right mouse-button menu.

One thing you might like to experiment with is what happens if you either leave a text box empty or enter the wrong data type (for example, entering a string into the third text box for conversion to a string). Depending on what you enter, you might see a different range of exceptions, a topic that is covered in more detail in Chapter 15.

Working with Arrays and Collections

Arrays and collections are two sides of the same coin, because they both provide ways of storing multiple copies of data types. For example, consider having to store several names, perhaps the authors of this book. You could store them in individual strings, but then what if you wanted to print them all? You’d need a statement for each variable. With an array or a collection, you need only one variable for multiple items. You can think of arrays as cells in a spreadsheet. A single dimensional array is a single row, with multiple cells, and a multi-dimensional array is multiple rows, each with multiple cells. Instead of cells, the term elements is generally used, and the index is the number of the element (the row or column number to continue the spreadsheet analogy).

Single Dimensional Arrays

Arrays are declared in much the same way as variables, but with the addition of square brackets after the variable type. For example:

string[] Names;

297