Home > Articles > Programming > Windows Programming

Hello, C#

This chapter attempts to capture your interest while grounding you in the fundamentals of C#. Stan Lippman introduces the language elements as they become necessary to implement a small first program. For those more traditionally minded, the chapter ends with a summary listing of the predefined language elements. He also covers simple types, as well as the namespace and exception-handling mechanisms.
This sample chapter was excerpted from C# Primer: A Practical Approach, by Stan Lippman.
This chapter is from the book

This chapter is from the book

My daughter has cycled through a number of musical instruments. With each one she is anxious to begin playing the classics—no, not Schubert or Schoenberg, but the Backstreet Boys and Britney Spears. Her various teachers, keen to keep her interest while grounding her in the fundamentals, have tended to indulge her. In a sense this chapter attempts the same precarious balance in presenting C#. In this context the classics are represented by Web Forms and Type Inheritance. The fundamentals are the seemingly mundane predefined language elements and mechanisms, such as scoping rules, arithmetic types, and namespaces. My approach is to introduce the language elements as they become necessary to implement a small first program. For those more traditionally minded, the chapter ends with a summary listing of the predefined language elements.

C# supports both integral and floating-point numeric types, as well as a Boolean type, a Unicode character type, and a high-precision decimal type. These are referred to as the simple types. Associated with these types is a set of operators, including addition (+), subtraction (-), equality (==), and inequality (!=). C# provides a predefined set of statements as well, such as the conditional if and switch statements and the looping for, while, and foreach statements. All of these, as well as the namespace and exception-handling mechanisms, are covered in this chapter.

1.1 A First C# Program

The traditional first program in a new language is one that prints Hello, World! on the user's console. In C# this program is implemented as follows:

// our first C# program
using System;
class Hello {
   public static void Main()
   {
       Console.WriteLine( "Hello, World!" );    }
}

When compiled and executed, this code generates the canonical

Hello, World!

Our program consists of four elements: (1) a comment, introduced by the double slash (//), (2) a using directive, (3) a class definition, and (4) a class member function (alternatively called a class method) named Main().

A C# program begins execution in the class member function Main(). This is called the program entry point. Main() must be defined as static. In our example, we declare it as both public and static.

public identifies the level of access granted to Main(). A member of a class declared as public can be accessed from anywhere within the program. A class member is generally either a member function, performing a particular operation associated with the behavior of the class, or a data member, containing a value associated with the state of the class. Typically, class member functions are declared as public and data members are declared as private. (We'll look at member access levels again as we begin designing classes.)

Generally, the member functions of a class support the behavior associated with the class. For example, WriteLine() is a public member function of the Console class. WriteLine() prints its output to the user's console, followed by a new-line character. The Console class provides a Write() function as well. Write() prints its output to the terminal, but without inserting a new-line character. Typically, we use Write() when we wish the user to respond to a query posted to the console, and WriteLine() when we are simply displaying information. We'll see a relevant example shortly.

As C# programmers, our primary activity is the design and implementation of classes. What are classes? Usually they represent the entities in our application domain. For example, if we are developing a library checkout system, we're likely to need classes such as Book, Borrower, and DueDate (an aspect of time).

Where do classes come from? Mostly from programmers like us, of course. Sometimes, it's our job to implement them. This book is designed primarily to make you an expert in doing just that. Sometimes the classes are already available. For example, the .NET System framework provides a DateTime class that is suitable for use in representing our DueDate abstraction. One of the challenges of becoming an expert C# programmer—and not a trivial one at that—is becoming familiar with the more than 1,000 classes defined within the .NET framework. I can't cover all of them here in this text, but we'll look at quite a number of classes, including support for regular expressions, threads, sockets, XML and Web programming, database support, and the new way of building a Windows application.

A challenging problem is how to logically organize a thousand or more classes so that users (that's us) can locate and make sense of them (and keep the names from colliding with one another). Physically, we can organize them within directories. For example, all the classes supporting Active Server Pages (ASP) can be stored in an ASP.NET directory under a root System.NET directory. This makes the organization reasonably clear to someone poking around the file directory structure.

What about within programs? As it turns out, there is an analogous organizing mechanism within C# itself. Rather than defining a physical directory, we identify a namespace. The most inclusive namespace for the .NET framework is called System. The Console class, for example, is defined within the System namespace.

Groups of classes that support a common abstraction are given their own namespace defined within the System namespace. For example, an Xml namespace is defined within the System namespace. (We say that the Xml namespace is nested within the System namespace.) Several namespaces in turn are nested within the Xml namespace. There is a Serialization namespace, for example, as well as XPath, Xsl, and Schema namespaces. These separate namespaces within the enclosing Xml namespace are factored out to encapsulate and localize shared functionality within the general scope of XML. This arrangement makes it easier to identify the support, for example, that .NET provides for the World Wide Web Consortium (W3C) XPath recommendation. Other namespaces nested within the System namespace include IO, containing file and directory classes, Collections, Threading, Web, and so on.

In a directory structure, we indicate the relationship of contained and containing directories with the backslash (\), at least under Windows—for example,

System\Xml\XPath

With namespaces, similar contained and containing relationships are indicated by the scope operator (.) in place of a backslash—for example,

System.Xml.XPath

In both cases we know that XPath is contained within Xml, which is contained within System.

Whenever we refer to a name in a C# program, the compiler must resolve that name to an actual declaration of something somewhere within our program. For example, when we write

	Console.WriteLine( "Hello, World" );

the compiler must somehow discover that Console is a class name and that WriteLine() is a member function within the Console class—that is, within the scope of the Console class definition. Because we have defined only the Hello class in our file, without our help the compiler is unable to resolve what the name Console refers to. Whenever the compiler cannot resolve what a name refers to, it generates a compile-time error, which stops our program from building:

C:\C#Programs\hello\hello.cs(7):

   The type or namespace name 'Console' does
   not exist in the class or namespace

The using directive in our program,

using System;

directs the compiler to look in the System namespace for any names that it cannot immediately resolve within the file it is processing—in this case, the file that contains the definition of our Hello class and its Main() member function.

Alternatively, we can explicitly tell the compiler where to look:

System.Console.WriteLine( "Hello, World" );

Some people—actually some very smart and otherwise quite decent people—believe that explicit listing of the fully qualified name—that is, the one that identifies the full set of namespaces in which a class is contained—is always preferable to a using directive. They point out that the fully qualified name clearly identifies where the class is found, and they believe that is useful information (even if it is repeated 14 times within 20 adjacent lines). I don't share that belief (and I really don't like all that typing). In my text—and this is one of the reasons we authors write books—the fully qualified name of a class is never used,1 except to disambiguate the use of a type name (see Section 1.2 for an illustration of situations in which this is necessary).

Earlier I wrote that classes come mostly either from other programmers or from libraries provided by the development system. Where else do they come from? The C# language itself. C# predefines several heavily used data types, such as integers, single- and double-precision floating-point types, and strings. Each has an associated type specifier that identifies the type within C#: int represents the primitive integer type; float, the primitive single-precision type; double, the double-precision type; and string, the string type. (See Tables 1.2 and 1.3 in Section 1.18.2 for a list of the predefined numeric types.)

For example, an alternative implementation of our simple program defines a string object initialized with the "Hello, World!" string literal:

 public static void Main() {
	string greeting = "Hello, World!"
	Console.WriteLine( greeting ); }

string is a C# keyword — that is, a word reserved by the C# language and invested with special meaning. public, static, and void are also keywords in the language. greeting is referred to as an identifier. It provides a name for an object of type string. Identifiers in C# must begin with either an underscore (_) or an alphabet character. The names are case sensitive, so greeting, Greeting, and Greeting1 each represent a unique identifier.

A common flash point among programmers centers on whether compound names should be separated by an underscore, as in xml_text_reader, or by capitalization of the first letter of each internal word, as in xmlTextReader. By convention, identifiers that represent class names usually begin with a capital letter, as in XmlTextReader.

Within a unit of program visibility referred to as a declaration space, or scope, identifiers must be unique. At local scope—that is, within a function body, such as within our definition of Main()—this is not a problem because we generally control the entire definition of any object within our function. As the extent of the scope widens—that is, as the number of programmers or organizations involved increases—the problem of unique identifiers becomes more difficult. This is where namespaces come into the picture.

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