Tải bản đầy đủ (.pdf) (81 trang)

Teach Yourself the C# Language in 21 Days phần 6 pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (808.6 KB, 81 trang )


Enter the contractor’s name: Matt Hebron
Enter ‘c’ for Contractor, ‘e’ for Employee then press ENTER: Z
===========================
Contractor: Amber Jones
Employee: Bejamin Andrews
Employee: Jacob Sams
Contractor: Matt Hebron
Person: Not an Employee or Contractor
===========================
This is a long listing compared to what you have been seeing. This listing only
partially implements everything it could do. One of today’s exercises will have
you expand on this listing.
The purpose of the listing is to enable you to enter people into the program. This is set
up to take five people; however, you could have the user enter people until a set value is
entered. The program prompts you to enter either an
‘e’ or a ‘c’ to indicate whether the
person is an employee or a contractor. Based on what you enter, it gives you a custom
prompt to enter the person’s name. You could also ask for additional information; how-
ever, this hasn’t been done here.
If the user enters a value other than an
‘e’ or ‘c’, the program fills the person’s name
with an error message. You most likely would want different logic than this. You should
also notice that although the program prompts for lowercase ‘e’ or ‘c’, uppercase letters
also work.
Most of the code should be familiar to you. The classes defined in this listing have been
scaled back to a minimum amount of code. Lines 26 and 45 were left in the listing as
comments. You will be asked to use these data members in one of today’s exercises.
In Line 63, you see the beginning of the
Main method for this application. Lines 69–102
contain a do while that loops for each person being entered. Lines 71–75 contain a


nested do while, which prompts the user to enter either an ‘e’ or a ‘c’ to indicate the
type of person being entered. Using a ReadLine in Line 74, the user’s answer is obtained.
Users who press Enter are prompted again.
When a value is entered,
if else statements are used to determine what processing
should occur. In Line 77, only the first character of the text entered by the user is
reviewed. The first character is stored in the 0 position of the string—buffer[0].
380 Day 10
ANALYSIS
Reusing Existing Code with Inheritance 381
10
If the value entered starts with a c, Lines 79–84 are executed. In Line 79, the user is
asked to enter a contractor’s name. The Write method is used instead of WriteLine so that
the reader can enter the name on the same line as the prompt. If you use WriteLine, a car-
riage return, line feed occurs and the user must enter the name on the next line.
In Line 80, the name is retrieved using the
ReadLine method. In Line 82, a contractor
object is created named contr. This object is initialized with the name obtained from the
ReadLine method. In Line 83, this new object is then assigned to the myCompany array.
Because myCompany is an array of Person,thecontr variable is assigned to the array as a
Person type. Because Person is a base type for Contractor, you can do this, as you learned
earlier today.
In Lines 106–123, the program again loops through the
myCompany array. This time, each
element in the array is printed to the screen. In Line 110, the element in the array is
checked to see whether it is an Employee. If it is, a custom output for employees is dis-
played. If not, the if statement in Line 115 is checked to see whether it is a Contractor. If
so, a message is printed. If not, a message is printed indicating that it is just a Person.
Line 124 prints a dashed line to help format the output. The program then ends.
Using

is and as enables you to store different data types in a single array, provided that
they work with the same base class. Because all objects inherit from Object, you will
always have a base class that works in this manner. This listing illustrates key features of
object-oriented programming.
Summary
Today’s lesson was long; however, it is also one of the most important. In today’s lesson,
you learned about inheritance. You learned how to create base classes and how to derive
from them. Additionally, you learned different keywords—such as abstract, virtual, and
protected—that can impact what you can do with a base class and a derived class. You
also learned how to seal a class to prevent inheritance.
Later in the day, you learned how to work with objects using types other than their own.
You learned that an object can be assigned or accessed using a type in any of its base
classes. Additionally, you learned that you can cast an object to a different type using the
as keyword. The as keyword operates similarly to a cast operation, except that, with an
error, a null is set instead of an exception being thrown. You also learned that you can
use the is keyword to evaluate what type an object is.
Q&A
Q Can you inherit from a base class written in a language other than C#?
A Yes. One of the features of .NET is that classes can inherit from classes written in
other languages. This means that your C# classes can be derived from classes of
other languages. Additionally, programmers of other languages can use your C#
classes as base classes.
Q Today’s lesson presented an example of assigning a derived class to a base
class in Listing 10.3. Can you assign a base class to a derived class?
A Yes, if you are careful. In Listing 10.3, a base class was assigned an object from a
derived class. Although only the items available via the base class constructs can
be used, the other portions of the derived class are not lost. It is possible to assign a
derived class the value of a base class if you know that the base class was assigned
an object of the derived class’s type. This assignment is done with a cast. In Listing
10.3, it would not be an error to do the following after Line 55:

Employee you = (Employee) Brad;
This is valid because Brad was assigned with an Employee object. If Brad was not an
Employee object, this line of code would throw an invalid cast exception,
(System.InvalidCastException).
Q What is data or method hiding?
A Data or method hiding occurs when you create a method or data element in a
derived class that replaces a base method or data element. This occurs when the
new
keyword is used to create the new class.
Q What are upcasting and downcasting?
A Downcasting is forcing an object to a type of a class derived from it. Upcasting is
casting an object to a data type of a base class. Upcasting is considered safe to do
and is an implicit operation in C#. Downcasting is considered unsafe. To downcast,
you must explicitly force the conversion.
Q What is composition? Is it an object-oriented term?
A Many people confuse inheritance with composition, but they are different. With
composition, one object is used within another object. Figure 10.4 is a composition
of many circles. This is different from the sphere in the previous example. The
sphere is not composed of a circle; it is an extension of the circle. To summarize
the difference between composition and inheritance, composition occurs when one
class (object) has another within it. Inheritance occurs when one class (object) is an
expansion of another.
382 Day 10
Reusing Existing Code with Inheritance 383
10
Workshop
The Workshop provides quiz questions to help you solidify your understanding of the
material covered and exercises to provide you with experience in using what you’ve
learned. Try to understand the quiz and exercise answers before continuing to tomorrow’s
lesson. Answers are provided on the CD.

Quiz
1. In C#, how many classes can be used to inherit from to create a single new class?
2. Which of the following is the same as a base class?
a. Parent class
b. Derived class
c. Child class
3. What access modifier is used to protect data from being used outside a single
class? What access modifier will enable data to be used by only a base class and
classes derived from the base class?
4. How is a base class’s method hidden?
FIGURE 10.4
A snowman made of
circles.
5. What keyword can be used in a base class to ensure that a derived class creates its
own version of a method?
6. What keyword is used to prevent a class from being inherited?
7. Name two methods that all classes have.
8. What class is the ultimate base class from which all other classes are derived?
9. What does boxing do?
10. What is the
as keyword used for?
Exercises
1. Write a method header for declaring a constructor for the ABC class that receives
two arguments, ARG1 and ARG2, that are both integers. This constructor should call a
base constructor and pass it to the ARG2 integer. This should be done in the method
header:
public ABC( int ARG1, int ARG2) : base( ARG2 )
{
}
2. Modify the following class to prevent it from being used as a base class:

1: class aLetter
2: {
3: private static char A_ch;
4:
5: public char ch
6: {
7: get { return A_ch; }
8: set { A_ch = value; }
9: }
10:
11: static aLetter()
12: {
13: A_ch = ‘X’;
14: }
15: }
3. Bug Buster: There is a problem with the following code. Which lines are in error?
// Bug Buster
// Class definition for Person would need to be included here
class NameApp
{
public static void Main()
{
384 Day 10
Reusing Existing Code with Inheritance 385
10
Person me = new Person();
Object you = new Object();
me = you;
System.Console.WriteLine(“Type: {0}”, me.GetType());
}

}
4. On Your Own: Modify Listing 10.9 to set the value of hireyear or company. Print
these values, when appropriate, with the output that is displayed.

DAY
11
WEEK 2
Formatting and
Retrieving Information
The last few days, you covered a lot of hard-core C# development topics that
will be critical to your development of professional-level applications. Before
trudging into additional hard-core topics, today’s lesson offers some diversion.
Today you…
• Review the difference between input and output.
• Discover more of the formatting options available when displaying infor-
mation in the console.
• Get a detailed explanation of reading information from the console.
• Learn how to parse information read from the console.
• Format and work with strings.
• Examine the concept of streams.
• Manipulate basic file information.
Understanding Console Input and Output
You’ve seen the terms input and output. In today’s lesson, you step back and focus on
providing output in a much better presentation format. Additionally, you learn a little
more about getting information from your users via input from the console.
You also learn a lot more about strings in today’s lessons. The
Write and WriteLine meth-
ods actually do string formatting behind the scenes. In today’s lesson, you learn how to
format these strings using other methods.
Formatting Information

When displaying information, it is often easiest to convert the information to a string
first. As you have already seen, the Write and WriteLine methods for the Console class use
strings for displaying output. Additionally, the .NET Framework provides a number of
methods and specifiers that can be used with strings. A specifier indicates that informa-
tion is to be formatted.
Format specifiers can be used with any string. The following sections cover a number of
format specifiers. This includes specifiers for working with each of the following:
• Standard numeric formats
• Currency
• Exponential numbers
• Exponentials
• Custom numeric formats
• Dates and times
• Enumerators
You can use these format specifiers in several ways. The most obvious way is to use the
specifiers with the
Write and WriteLine methods to provide additional formatting.
You also can use the format specifiers when calling the
ToString method. As you learned
in yesterday’s lesson, the Object class contains a ToString method. As you know, because
all classes are derived from Object, all objects have access to a ToString method. In
388 Day 11
Today’s lesson contains much more reference information than most of the
other days in this book. You should find this reference material valuable.
Note
Formatting and Retrieving Information 389
11
classes such as the Int32 class, this method can be passed a formatting specifier to format
the data. For example, if var is an integer variable containing the value 123, by using the
currency formatter (“C”), the following line

var.ToString(“C”);
returns this value:
$123.00
A third time to use a specifier is with the string data type. string has a static method
named
Format. Because Format is a static method, it can be used directly with the class as
string.Format. The format for using this method follows the same format as the parame-
ters of the Console display methods:
string newString = string.Format(“format_string”, value(s) );
Here, newString is the new string that will be formatted. format_string is a string that
contains formatting specifiers. These specifiers are the same as those that can be used in
Write and WriteLine. value(s) contains the values that will be formatted into the string.
You will learn more about formatting values as you learn about some of the
specifiers.
Note
The character C is the format specifier for currency. As stated previously, you can indi-
cate this format to the ToString method by passing it between quotes as an argument.
When formatting information within a string, such as with WriteLine, you include this
format specifier with the variable placeholder. The following is the basic format:
{hldr:X#}
Here, hldr is the placeholder number for the variable. X is the specifier used to format the
number. To format the number as currency, this would be C. The # is an optional value,
which is the number of digits you want. This number can do different types of padding,
depending on the specifier. With the currency specifier, this number indicates the number
of decimal places. Listing 11.1 presents the three ways of using specifiers that were men-
tioned earlier. It presents a small example of using the currency and other specifiers.
More details are provided later today on these and other specifiers.
LISTING 11.1 FormatIt.cs—Basic Formatting Methods
1: // FormatIt.cs - Different places for specifiers
2: // to be used.

3: //
4:
5: using System;
6:
7: class FormatIt
8: {
9: public static void Main()
10: {
11: int var = 12345;
12:
13: // Format using WriteLine
14:
15: Console.Write(“You can format text using Write”);
16: Console.WriteLine(“ and WriteLine. You can insert”);
17: Console.Write(“variables (such as {0}) into a string”, var );
18: Console.WriteLine(“ as well as do other formatting!”);
19: Console.WriteLine(“\n{0:C}\n{0:C4}”, var);
20: Console.WriteLine(“\n{0:f}\n{0:f3}”, var);
21:
22:
23: // Format using ToString
24:
25: string str1 = var.ToString(“C”);
26: string str2 = var.ToString(“C3”);
27: string str3 = var.ToString(“E8”);
28:
29: Console.WriteLine(“\nYou can also format using ToString”);
30: Console.WriteLine(str1);
31: Console.WriteLine(str2);
32: Console.WriteLine(str3);

33:
34: // Formatting with string.Format
35:
36: string str4 = string.Format(“\nOr, you can use string.Format: “);
37: string str5 = string.Format(“Nbr {0:F3} \n{0:C} \n{0:C0}”, var);
38:
39: Console.WriteLine(str4);
40: Console.WriteLine(str5);
41: }
42: }
You can format text using Write and WriteLine. You can insert
variables (such as 12345) into a string as well as do other formatting!
$12,345.00
$12,345.0000
390 Day 11
OUTPUT
Formatting and Retrieving Information 391
11
12345.00
12345.000
You can also format using ToString
$12,345.00
$12,345.000
1.23450000E+004
Or, you can use string.Format:
Nbr 12345.000
$12,345.00
$12,345
A full analysis of this listing isn’t provided here. Instead, this listing is presented
to touch on some of the formatting you can do. You can see that formatting is

done in this listing: The var number is formatted as currency, a decimal number, and an
exponential. More important to notice here is that the numbers included after the speci-
fier helped determine the number of decimals or zero positions included.
Formatting Numbers
You can use a number of format specifiers to format numeric values. Table 11.1 lists
these specifiers.
TABLE 11.1 Characters Used for Numeric Formatting
Specifier Description Default Format Example Output
C or c Currency $xx,xxx.xx $12,345.67
($xx,xxx.xx) ($12,345.67)
D
or d Decimal xxxxxxx 1234567
-xxxxxxx -1234567
E
or e Exponential x.xxxxxxE+xxx 1.234567E+123
x.xxxxxxe+xxx 1.234567e+123
-x.xxxxxxxE+xxx -1.234567E+123
-x.xxxxxxxe+xxx -1.234567e+123
x.xxxxxxE-xxx 1.234567E-123
x.xxxxxxe-xxx 1.234567e-123
-x.xxxxxxxE-xxx -1.234567E-123
-x.xxxxxxxe-xxx -1.234567e-123
F
or f Fixed point xxxxxx.xx 1234567.89
-xxxxx.xx -1234567.89
ANALYSIS
N or n Numeric xx,xxx.xx 12,345.67
-xx,xxx.xx -12,345.67
X or x Hexadecimal 12d687 12D687
G or g General Varies (uses the most compact format)

R or r Round-trip Maintains precession when numbers are converted to and then
back from a string
You can use these and the other format specifiers in today’s lesson in the ways described
earlier. When using the specifiers with the ToString method, you enclose the appropriate
character in quotation marks and pass it as a parameter. You saw the earlier example of
123 being formatted as currency:
string newString = var.ToString(“C”);
This line of code results in newString containing the value $123.00. The following sec-
tions discuss each of these formats briefly.
392 Day 11
TABLE 11.1 continued
Specifier Description Default Format Example Output
The formatting specifiers might differ depending on your system’s locale
settings.
Caution
Standard Formats (Fixed, Decimal, Numeric)
The standard format specifiers work with their related number types. F works for
floating-point numbers. D works with standard whole numbers, such as integers and
longs. If you try to use D with a floating-point number, you will get an exception.
The number specifier (
N) adds two decimal places and commas to the number’s format.
This can be used to obtain a much nicer format than the default format for numbers.
Formatting Currency
By now, you should know that the currency specifier is C. You can use C by itself to have
currency displayed with two decimal positions. If you want to avoid decimals, use C0.
The 0 indicates that no decimal positions should be included. If you want to get a differ-
ent number of decimal places in your currency display, simply change the 0 to the num-
ber of decimal places you would like.
Formatting and Retrieving Information 393
11

Formatting Exponential Numbers
Exponential numbers are often presented in scientific notation because of their overly
large, or overly small, size. The E and e specifiers can be used to format these numbers.
You should note that the case of the E in the format specifier is the same case that will be
used in the output.
General Formatting of Numbers
The general formatting specifier (G or g) is used to format a number into the smallest
string representation possible. Based on the number, this formatter determines whether
an exponential representation or a standard format results in the smallest string.
Whichever is smaller is returned. Listing 11.2 illustrates the different formats that this
specifier can return.
LISTING 11.2 General.cs—Using the General Specifier
1: // General.cs - Using the General format specifier
2: //
3: using System;
4:
5: class General
6: {
7: public static void Main()
8: {
9: float fVal1 = .000000789F;
10: float fVal2 = 1.2F;
11:
12: Console.WriteLine(“f1 ({0:f}). Format (G): {0:G}”, fVal1);
13: Console.WriteLine(“f2 ({0:f}). Format (G): {0:G}”, fVal2);
14: }
15: }
f1 (0.00). Format (G): 7.89E-07
f2 (1.20). Format (G): 1.2
This listing initializes and prints two variables. In Lines 9–10, two float variables

are created. One is a very small decimal value, and the other is a simple number.
In Lines 12–13, these values are written to the console. The first placeholder in each of
these lines displays the floating-point value as a fixed-point number using the
F specifier.
The second placeholder prints the same variable in the general format using the G format.
In the output, fVal1 is much more concise as an exponential number, and fVal2 is more
concise as a regular number.
OUTPUT
ANALYSIS
Formatting Hexadecimal Numbers
Hexadecimal numbers are numbers based on the base 16 number system. This number
system is often used with computers. Appendix C, “Understanding Number Systems”
covers using hexadecimal. The letter x—either uppercase or lowercase—is used to spec-
ify a hexadecimal number. The hexadecimal specifier automatically converts and prints a
value as a hexadecimal value.
Maintaining Precession (Round-Tripping)
When you convert a number from one format to another, you run the risk of losing preci-
sion. A specifier has been provided to help maintain precision in case you want to con-
vert a string back to a number: the R (or r) specifier. By using this specifier, the runtime
tries to maintain the precision of the original number.
Creating Custom Formats Using Picture Definitions
Sometimes you will want to have more control over a number’s format. For example,
you might want to format a driver’s license number or Social Security number with
dashes. You might want to add parentheses and dashes to a phone number. Table 11.2
presents some of the formatting characters that can be used with the specifiers to create
custom formats for output. Listing 11.3 provides examples of these specifiers.
TABLE 11.2 Formatting Characters for Picture Definitions
Specifier Description
0 Zero placeholder. Filled with digit, if available.
# Blank placeholder. Filled with digit, if available.

. Displays a period. Used for decimal points.
, Uses a comma for separating groups of numbers. It can also be used as a multi-
plier (see Listing 11.3).
% Displays the number as a percentage value (for example, 1.00 is 100%).
\ Used to indicate that a special character should be printed. This can be one of the
escape characters, such as the newline character (
\n).
‘xyz’ Displays text within the apostrophes.
“xyz” Displays text within the quotes.
394 Day 11
Formatting and Retrieving Information 395
11
LISTING 11.3 Picts.cs—Using the Picture Specifiers
1: // Picts.cs - Using picture specifiers
2: //
3:
4: using System;
5:
6: class Picts
7: {
8: public static void Main()
9: {
10: int var1 = 1234;
11: float var2 = 12.34F;
12:
13: // Zero formatter
14: Console.WriteLine(“\nZero ”);
15: Console.WriteLine(“{0} >{0:0000000}”, var1);
16: Console.WriteLine(“{0} >{0:0000000}”, var2);
17:

18: // Space formatter
19: Console.WriteLine(“\nSpace ”);
20: Console.WriteLine(“{0} >{0:0####}< ”, var1);
21: Console.WriteLine(“{0} >{0:0####}< ”, var2);
22:
23: // Group separator and multiplier (,)
24: Console.WriteLine(“\nGroup Multiplier ”);
25: Console.WriteLine(“{0} >{0:0,,}< ”, 1000000);
26: Console.WriteLine(“Group Separator ”);
27: Console.WriteLine(“{0} >{0:##,###,##0}< ”, 2000000);
28: Console.WriteLine(“{0} >{0:##,###,##0}< ”, 3);
29:
30: // Percentage formatter
31: Console.WriteLine(“\nPercentage ”);
32: Console.WriteLine(“{0} >{0:0%}< ”, var1);
33: Console.WriteLine(“{0} >{0:0%}< ”, var2);
34:
35: // Literal formatting
36: Console.WriteLine(“\nLiteral Formatting ”);
37: Console.WriteLine(“{0} >{0:’My Number: ‘0}< ”, var1);
38: Console.WriteLine(“{0} >{0:’My Number: ‘0}< ”, var2);
39: Console.WriteLine(“\n{0} >{0:Mine: 0}< ”, var1);
40: Console.WriteLine(“{0} >{0:Mine: 0}< ”, var2);
41: }
42: }
Zero
1234 >0001234
12.34 >0000012
Space
1234 >01234<

12.34 >00012<
Group Multiplier
1000000 >1<
Group Separator
2000000 >2,000,000<
3 >3<
Percentage
1234 >123400%<
12.34 >1234%<
Literal Formatting
1234 >My Number: 1234<
12.34 >My Number: 12<
1234 >Mine: 1234<
12.34 >Mine: 12<
This listing uses the format specifiers in Table 11.2 and applies them to two vari-
ables. Looking at the comments and the output, you can see how a number of the
specifiers work.
Formatting Negative Numbers
Sometimes you also when you want a negative number treated differently than a positive
number. The specifiers that you have learned about will work with both positive and neg-
ative numbers.
The placeholder for specifying the format can actually be separated into either two or
three sections. If the placeholder is separated into two sections, the first is for positive
numbers and
0, and the second is for negative numbers. If it is broken into three sections,
the first is for positive values, the middle is for negative values, and the third is for 0.
The placeholder is broken into these sections using a semicolon. The placeholder number
is then included in each. For example, to format a number to print with three levels of
precision when positive, five levels when negative, and no levels when
0, you do the fol-

lowing:
{0:D3;D5;’0’}
Listing 11.4 presents this example in action, along with a couple of additional examples.
396 Day 11
OUTPUT
ANALYSIS
Formatting and Retrieving Information 397
11
LISTING 11.4 ThreeWay.cs.
1: // ThreeWay.cs - Controlling the formatting of numbers
2: //
3:
4: using System;
5:
6: class ThreeWay
7: {
8: public static void Main()
9: {
10: Console.WriteLine(“\nExample 1 ”);
11: for ( int x = -100; x <= 100; x += 100 )
12: {
13: Console.WriteLine(“{0:000;-00000;’0’}”, x);
14: }
15:
16: Console.WriteLine(“\nExample 2 ”);
17: for ( int x = -100; x <= 100; x += 100 )
18: {
19: Console.WriteLine(“{0:Pos: 0;Neg: -0;Zero}”, x);
20: }
21:

22: Console.WriteLine(“\nExample 3 ”);
23: for ( int x = -100; x <= 100; x += 100 )
24: {
25: Console.WriteLine(“{0:You Win!;You Lose!;You Broke Even!}”, x);
26: }
27: }
28: }
Example 1
-00100
0
100
Example 2
Neg: -100
Zero
Pos: 100
Example 3
You Lose!
You Broke Even!
You Win!
This listing helps illustrate how to break the custom formatting into three pieces.
A for loop is used to create a negative number, increment the number to 0, and
finally increment it to a positive number. The result is that the same WriteLine can be
OUTPUT
ANALYSIS
used to display all three values. This is done three separate times for three different
examples.
In Line 13, you see that the positive value will be printed to at least three digits because
there are three zeros in the first formatting position. The negative number will include a
negative sign followed by at least five numbers. You know this because the dash is
included in the format for the negative sign, and there are five zeros. If the value is equal

to
0,a 0 will be printed.
In the second example, text is included with the formatting of the numbers. This is also
done in the third example. The difference is that, in the second example, zero placehold-
ers are also included so that the actual numbers will print. This is not the case with the
third example, in which only text is displayed.
As you can see by all three of these examples, it is easy to cause different formats to be
used based on the sign (positive or negative) of a variable.
Formatting Date and Time Values
Date and time values can also be formatted. A number of specifiers can help you format
everything from the day of the week to the full data and time string. Before learning
about these format characters, you should understand how to obtain the date and time.
Getting the Date and Time
C# and the .NET Framework provide a class for storing dates and times—the DateTime
class located in the System namespace. The DateTime class stores both the full date and the
full time.
The
DateTime class has a number of properties and methods that you will find useful.
Additionally, there are a couple of static members. The two static properties that you will
likely use are Now and Today. Now contains the date and time for the moment the call is
made. Today returns just the current date. Because these are static properties, their values
can be obtained using the class name rather than an instant name:
DateTime.Now
DateTime.Today
You can review the online documents for information on all the methods and properties
of the DateTime class. A few of the ones that you might find useful are shown here:
Date Returns the date portion of a DateTime object
Month Returns the month portion of a DateTime object
Day Returns the day of the month of a DateTime object
398 Day 11

Formatting and Retrieving Information 399
11
Year Returns the year portion of the DateTime object
DayOfWeek Returns the day of the week of a DateTime object
DayOfYear Returns the day of the year of a DateTime object
TimeOfDay Returns the time portion of a DateTime object
Hour Returns the hour portion of a DateTime object
Minute Returns the minutes portion of a DateTime object
Second Returns the seconds portion of a DateTime object
Millisecond Returns the milliseconds component of a DateTime object
Ticks Returns a value equal to the number of 100-nanosecond ticks for the
given DateTime object
Although the DateTime.Today property includes a time value, it is not the
current time. The DateTime.Today property gives you only a valid date—it
does not give you the current time.
Note
Formatting the Date and Time
A number of specifiers can be used with dates, times, or both. These include the capabil-
ity to display information in short and long format. Table 11.3 contains the date and time
specifiers.
TABLE 11.3 Date and Time Formatting Characters
Specifier Description Default Format Example Output
d Short date mm/dd/yyyy 5/6/2001
D
Long date day, month dd, yyyy Sunday, May 06, 2001
f
Full date/ day, month dd, Sunday, May 06, 2001 12:30 PM
short time yyyy hh:mm AM/PM
F
Full date/ day, month dd, Sunday, May 06, 2001 12:30:54 PM

full time yyyy HH:mm:ss AM/PM
g
Short date/ mm/dd/yyyy HH:mm 6/5/2001 12:30 PM
short time
G Short date/ mm/dd/yyyy hh:mm:ss 6/5/2001 12:30:54 PM
long time
M or m Month day month dd May 06
R or r RFC1123 ddd, dd Month yyyy Sun, 06 May 2001 12:30:54 GMT
hh:mm:ss GMT
s
Sortable yyyy-mm-dd hh:mm:ss 2001-05-06T12:30:54
t
Short time hh:mm AM/PM 12:30 PM
T
Long time hh:mm:ss AM/PM 12:30:54 PM
u
Sortable yyyy-mm-dd hh:mm:ss 2001-05-06 12:30:54Z
(universal)
U Sortable day, month dd, yyyy Sunday, May 06, 2001 12:30:54 PM
(universal) hh:mm:ss AM/PM
Y or y Year/month month, yyyy May, 2001
400 Day 11
TABLE 11.3 continued
Specifier Description Default Format Example Output
s is used as a specifier for printing a sortable date. Note that this is a lower-
case s. An uppercase S is not a valid format specifier and generates an
exception if used.
Caution
The date and time specifiers are easy to use. Listing 11.5 defines a simple date variable
and then prints it in all the formats presented in Table 11.3.

LISTING 11.5 DtFormat.cs—The Date Formats
1: // DtFormat.cs - date/time formats
2: //
3:
4: using System;
5:
6: class DtFormat
7: {
8: public static void Main()
9: {
10: DateTime CurrTime = DateTime.Now;
11:
12: Console.WriteLine(“d: {0:d}”, CurrTime );
13: Console.WriteLine(“D: {0:D}”, CurrTime );
14: Console.WriteLine(“f: {0:f}”, CurrTime );
15: Console.WriteLine(“F: {0:F}”, CurrTime );
16: Console.WriteLine(“g: {0:g}”, CurrTime );
17: Console.WriteLine(“G: {0:G}”, CurrTime );
18: Console.WriteLine(“m: {0:m}”, CurrTime );
19: Console.WriteLine(“M: {0:M}”, CurrTime );
Formatting and Retrieving Information 401
11
20: Console.WriteLine(“r: {0:r}”, CurrTime );
21: Console.WriteLine(“R: {0:R}”, CurrTime );
22: Console.WriteLine(“s: {0:s}”, CurrTime );
23: // Console.WriteLine(“S: {0:S}”, CurrTime ); // error!!!
24: Console.WriteLine(“t: {0:t}”, CurrTime );
25: Console.WriteLine(“T: {0:T}”, CurrTime );
26: Console.WriteLine(“u: {0:u}”, CurrTime );
27: Console.WriteLine(“U: {0:U}”, CurrTime );

28: Console.WriteLine(“y: {0:y}”, CurrTime );
29: Console.WriteLine(“Y: {0:Y}”, CurrTime );
30: }
31: }
d: 1/24/2003
D: Friday, January 24, 2003
f: Friday, January 24, 2003 8:43 PM
F: Friday, January 24, 2003 8:43:04 PM
g: 1/24/2003 8:43 PM
G: 1/24/2003 8:43:04 PM
m: January 24
M: January 24
r: Fri, 24 Jan 2003 20:43:04 GMT
R: Fri, 24 Jan 2003 20:43:04 GMT
s: 2003-01-24T20:43:04
t: 8:43 PM
T: 8:43:04 PM
u: 2003-01-24 20:43:04Z
U: Saturday, January 25, 2003 1:43:04 AM
y: January, 2003
Y: January, 2003
LISTING 11.5 continued
OUTPUT
Note that, on some systems, the date formatting might include zero
padding. For example, using the mono compiler, dates appear as 01/24/2003
instead of 1/24/2003.
Note
In Line 10, this listing declares an object to hold the date and time. This is done
using the DateTime class. This object is named CurrTime, and it is assigned the sta-
tic value from the DateTime class, Now, which provides the current date and time. Looking

at the output, you can see that I ran this listing midday in May. Lines 12–29 present this
same date and time in all the date/time formats.
Line 23 is commented. This line uses the
S specifier, which is not legal. If you uncom-
ment this line, you will see that the listing throws an exception.
ANALYSIS
Displaying Values from Enumerations
When you worked with enumerators on Day 7, “Storing More Complex Stuff: Structures,
Enumerators, and Arrays,” you saw that the output when using Write and WriteLine dis-
played the descriptive value of the enumerator rather than the numeric value. With string
formatting, you can control the numeric value or the text value. You can also force a
hexadecimal representation to be displayed. Table 11.4 presents the formatting characters
for enumerators. Listing 11.6 presents a listing using these key values in this table.
TABLE 11.4 Formatting Characters for Enumerators
Specifier Description
D or d Displays the numeric value from the enumerator element
G or g Displays the string value from the enumerator element
X or x Displays the hexadecimal equivalent of the numeric value from the enumerator
element
LISTING 11.6 Enums.cs—Formatting Enumeration Values
1: // Enums.cs - enumerator formats
2: //
3:
4: using System;
5:
6: class Enums
7: {
8: enum Pet
9: {
10: Cat,

11: Dog,
12: Fish,
13: Snake,
14: Rat,
15: Hamster,
16: Bird
17: }
18:
19: public static void Main()
20: {
21: Pet myPet = Pet.Fish;
22: Pet yourPet = Pet.Hamster;
23:
24: Console.WriteLine(“Using myPet: “);
25: Console.WriteLine(“d: {0:d}”, myPet );
26: Console.WriteLine(“D: {0:D}”, myPet );
402 Day 11
Formatting and Retrieving Information 403
11
27: Console.WriteLine(“g: {0:g}”, myPet );
28: Console.WriteLine(“G: {0:G}”, myPet );
29: Console.WriteLine(“x: {0:x}”, myPet );
30: Console.WriteLine(“X: {0:X}”, myPet );
31:
32: Console.WriteLine(“\nUsing yourPet: “);
33: Console.WriteLine(“d: {0:d}”, yourPet );
34: Console.WriteLine(“D: {0:D}”, yourPet );
35: Console.WriteLine(“g: {0:g}”, yourPet );
36: Console.WriteLine(“G: {0:G}”, yourPet );
37: Console.WriteLine(“x: {0:x}”, yourPet );

38: Console.WriteLine(“X: {0:X}”, yourPet );
39: }
40: }
Using myPet:
d: 2
D: 2
g: Fish
G: Fish
x: 00000002
X: 00000002
Using yourPet:
d: 5
D: 5
g: Hamster
G: Hamster
x: 00000005
X: 00000005
This listing creates an enum that holds pets. In Lines 21–22, two objects are
created, myPet and yourPet, that are used to illustrate the format specifiers.
Lines 24–30 use the specifiers with the myPet object. Lines 32–38 use yourPet. As you
can see by the output, the case of the specifiers doesn’t matter.
Working More Closely with Strings
Now that you know all about formatting strings, it is worth stepping back and learning a
few more details about string specifics. Recall that strings are a special data type that can
hold textual information.
As you should know,
string is a C# keyword; it is simply a different name for the String
class in the System namespace. As such, string has all the methods and properties of the
String class.
LISTING 11.6 continued

OUTPUT
ANALYSIS

×