Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

You'll use the classes in the System namespace in almost every .NET application. All the data types are represented, for example. Two classes in particular deserve special mention: System::Console and System::String.

The System::Console Class

System::Console, called System.Console in the documentation, represents the screen and keyboard in a simple console application. After you add a using statement to your file so you don't have to type System:: every time, the Console class is simple to use. To write a line of text to the screen, you use the static function WriteLine():

Console::WriteLine("Calculations in Progress");

If you want to write text without a following line break, use the Write() function instead.

To read a line of text from the keyboard, first you should write out a line to prompt the users, and then read the entire line into a System::String object with the static ReadLine() function:

Console::WriteLine("Enter a sentence:");
String* sentence = Console::ReadLine();

If you want to read in something more complicated than a single string, there really isn't any support for it within the Console class, nor the classes in the System::IO namespace covered later in this chapter. You can read it into a string and then use string member functions to separate it into the pieces you want.

If you want to write formatted output, there's an overload of WriteLine that's reminiscent of printf(), except that you don't have to tell the function the type of each parameter. For example

Console::WriteLine("The time is {0} at this moment", 
          System::DateTime::Now.ToShortTimeString() );

You can write out a number of parameters at once. Use the placeholders, the things in brace brackets in the format string, to call for the parameter you want. As you can see, the count is zero-based. Here's an example:

Console::WriteLine("{0} lives at {1}", name, address);

The System::String and System::Stringbuilder Classes

The String class represents a string, such as "Hello" or "Kate Gregory". That's familiar ground for any programmer. But working with .NET strings can be quite strange for an experienced C++ or MFC programmer. They are certainly very far removed from the arrays of characters that you might be used to working with.

If you've ever worked with the MFC class CString, you've probably written code like this:

CString message = "Value of x, ";
message += x;
message += "is over limit.";

You might guess that the .NET equivalent would be

String* message = "Value of x, ";
message += x;
message += "is over limit.";

This just gets you a lot of strange compiler errors about illegal pointer arithmetic. The message variable is a pointer to a String instance, so you can't use the + operator. You can't do it in a single line either, like this:

String* message = "Value of x, " + x + "is over limit.";

The bottom line is that you can't treat .NET strings like C++ or C strings. So how do you build a string from several substrings, or from several pieces in general? If you want to build it so you can write it out, forget building the string, and use formatted output as described in the previous section. Or use the Format() method, which is reminiscent of sprintf(), and of the Format() method of the old MFC class CString. But if you need to build a string in little bits and pieces, your best choice is a companion class called StringBuilder, from the System::Text namespace. You use a string builder like this:

String* name = "Kate";
System::Text::StringBuilder* sb = new System::Text::StringBuilder("Hello ");
sb->Append(name);

Using a string builder is more efficient than modifying a string as you go, because .NET strings actually can't be modified; instead, a whole new one is created with your changes, and the old one is cleaned up later. StringBuilder has all sorts of useful methods like Append(), Insert(), Remove(), and Replace() that you can use to work on your string. When it's ready, just pass the string builder object to anything that's expecting a string:

Console::WriteLine(sb);

The framework gets the built string from the string builder and passes it to the function for you.

The String class has its own useful methods too. Consider the problem mentioned earlier—reading something other than a single string from the keyboard. The easiest way for you to tackle the problem is to write code that reads the line of input into a string, and then works with it. Here's a simple example:

Console::WriteLine("Enter three integers:");
String* input = Console::ReadLine();
String* numbers[] = input->Split(0);
int a1 = Convert::ToInt32(numbers[0]);
int a2 = Convert::ToInt32(numbers[1]);
int a3 = Convert::ToInt32(numbers[2]);

This code uses the Split() member function of the String class. It splits a String into an array of strings based on a separator character. If you pass in a null pointer (0), as in this example, it splits the string based on whitespace such as spaces or tabs, which is perfect for this situation. The ToInt32() method of the Convert class converts a String to an integer.

If you already know how to manipulate strings, you might appreciate a quick "cheat sheet" for the String class. Table 3.1 is just such a summary.

Table 3.1 String Functions

C Runtime

MFC CString

System::String

strcpy

operator=

operator=

strcat

operator+=

Append

strchr

Find

IndexOf

strcmp

operator == or Compare

Compare

strlen

GetLength()

Length

strtok

n/a

Split

[]

[] or GetAt()

Chars

sprintf

Format

Format

n/a

Left or Right or Mid

Substring


If you've worked with strings in other languages, you'll appreciate System::String functions such as PadLeft(), PadRight(), Remove(), and StartsWith(). If those names aren't familiar to you, check the Visual C++ documentation. You might be able to do what you want with a single function call!

The System::DateTime Structure

The DateTime structure represents a date or a time, or both. It has a number of useful constructors to create instances using a numeric date and time, or a number of ticks (useful when you're working with older C++ code). Here are some examples:

DateTime defaultdate;
Console::WriteLine(defaultdate.ToLongDateString());
DateTime Sept28(2003,9,28,14,30,0,0);
Console::Write(Sept28.ToShortDateString());
Console::Write(S" ");
Console::WriteLine(Sept28.ToShortTimeString());
DateTime now = DateTime::Now;
Console::WriteLine(now.ToString());

It can be intimidating to remember the parameters to the seven-integer constructor, but it's simple when you realize they go from largest to smallest: year, month, day, hour, minute, second, and millisecond. The millisecond parameter is optional and if you want, you can omit all the time parameters completely.

On September 17, 2003, this code produces the following output:

Monday, January 01, 0001
9/28/2003 2:30 PM
9/17/2003 1:17:41 PM

It matters that DateTime is a structure, not a class, because it is managed data. Managed classes can only be allocated on the heap with new; managed structures can only be allocated on the stack as in these examples.

To get the individual parts of a date, use these properties:

  • Day: The day of the month

  • Month: 1 to 12

  • Year: Always four digits

  • Hour: 0 to 23

  • Minute

  • Second

  • DayOfWeek: 0 means Sunday

  • Format: Creates a string based on the time and date, using a format string

The format string passed to Format() is either a single character representing one of a number of "canned" formats, or a custom format string. The most useful canned formats include

  • d: A short date, such as 12/19/00

  • D: A long date, such as Tuesday, December 19, 2000

  • f: A full time and date, such as Tuesday, December 19, 2000 17:49

  • g: A general time and date, such as 12/19/00 17:49

  • s: A sortable time and date, such as 2000-12-19 17:49:03

  • t: A short time, such as 17:49

  • T: A long time, such as 17:49:03

If none of the canned formats has what you need, you can make your own by passing in strings such as "MMMM d, yy" for "December 3, 02" or whatever else you desire. You can find all the format strings in the help installed with Visual Studio.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020