Home > Articles > Programming > Windows Programming

Hello, C#

This chapter is from the book

This chapter is from the book

1.18 A Basic Language Handbook for C#

The three things left undone for a complete implementation of our WordCount application are (1) to illustrate how to implement the timing diagnostics, (2) to show how to conditionally output tracing statements, and (3) to package our code into the WordCount class. This last item is so important that it deserves its own chapter—Chapter 2 to be exact.

We look at how to generate the tracing output in Section 5.5.2 in the discussion of the TraceListener class hierarchy. The timing support is presented in Section 8.6.3 in the discussion of interoperability with the Win32 API. The remainder of this section provides a brief handbook of the C# basic language in the form of a set of tables with brief commentary.

1.18.1 Keywords

Keywords are identifiers reserved by the language. They represent concepts or facilities of the basic C# language. abstract, virtual, and override, for example, specify different categories of dynamic functions that support object-oriented programming. delegate, class, interface, enum, event, and struct represent a variety of complex types that we can define. The full set of keywords is listed in Table 1.1.

Table 1.1 The C# Keywords

abstract

as

base

bool

break

byte

case

catch

char

checked

class

const

continue

decimal

default

delegate

do

double

else

enum

event

explicit

extern

false

finally

fixed

float

for

foreach

goto

if

implicit

in

int

interface

internal

is

lock

long

namespace

new

null

object

operator

out

override

params

private

protected

public

readonly

ref

return

sbyte

sealed

short

sizeof

stackalloc

static

string

struct

switch

this

throw

true

try

typeof

uint

ulong

unchecked

unsafe

ushort

using

virtual

void

while

 

 

 

 


A name cannot begin with a number. For example, 1_name is illegal but name_1 is OK. A name must also not match a language keyword, with the one proverbial exception: We can reuse a C# keyword name by prefixing it with @—for example,

 class @class 
{
  static void @static(bool @bool) 
	{
     if (@bool)
       Console.WriteLine( "true" );
     else Console.WriteLine( "false" );
	}		
}
class Class1
{
	 static void M { @class.@static( true ); }
}

This prefix option may prove useful in interfacing with other languages, in particular when a C# keyword is used as an identifier in the other programming language. (The @ character is not part of the identifier. Rather it provides a context for interpreting the keyword as an identifier.)

1.18.2 Built-in Numeric Types

Integral literals, such as 42 and 1024, are of type int. To indicate an unsigned literal value, the lower- or uppercase letter U is added as a suffix—for example, 42u, 1024U. To indicate a literal value of type long, we add a lower- or uppercase L as a suffix—for example, 42L, 1024l. (For readability, the upper case L is the preferred usage.) To specify a literal value that is both unsigned and long, we combine the two suffixes—for example, 42UL, 1024LU.

The sizes (whether the value is signed or unsigned) determine the range of values a type can hold. A signed byte, for example, holds the range -128 through 127, an unsigned byte the range 0 through 255, and so on.

However, using types smaller than int can be nonintuitive in some circumstances, and I find myself avoiding them except occasionally as class members. For example, the code sequence

sbyte s1 = 0;
s1 = s1 + 1; // error!

is flagged as an error with the following message:

 Cannot implicitly convert type 'int' to 'byte'

The rule is that the built-in numeric types are implicitly converted to a type as large as or larger. So int is implicitly promoted to double. But any conversion from a larger to a smaller type requires an explicit user conversion. For example, the compiler does not implicitly allow the conversion of double to int. That conversion must be explicit:

s1 = (sbyte) ( s1 + 1 ); // OK

Why, though, you might ask, is a conversion necessary when s1 is simply being incremented by 1? In C#, integral operations are carried out minimally through signed 32-bit precision values. This means that an arithmetic use of s1 results in a promotion of its value to int. When we mix operands of different types, the two are promoted to the smallest common type. For example, the type of the result of s1+1 is int.

When we assign a value to an object, as with our assignment of s1 here, the type of the right-hand value must match the type of the object. If the two types do not match, the right-hand value must be converted to the object's type or the assignment is flagged as an error.

By default, a floating-point literal constant, such as 3.14, is treated as type double. Adding a lower- or uppercase F as a suffix to the value turns it into a single-precision float value. Character literals, such as 'a', are placed within single quotes. Decimal literals are given a suffix of a lower- or uppercase M. (The decimal type is probably unfamiliar to most readers; Section 4.3.1 looks at it in more detail.) Table 1.2 lists the built-in numeric types.

Table 1.2 The C# Numeric Types

Keyword

Type

Usage

sbyte

Signed 8-bit int

sbyte sb = 42;

short

Signed 16-bit int

short sv = 42;

int

Signed 32-bit int

int iv = 42;

long

Signed 64-bit int

long lv = 42, lv2 = 42L, lv3 = 42l;

byte

Unsigned 8-bit int

byte bv = 42, bv2 = 42U, bv3 = 42u;

ushort

Unsigned 16-bit int

ushort us = 42;

uint

Unsigned 32-bit int

uint ui = 42;

long

Unsigned 64-bit int

ulong ul = 42, ul2 = 4ul, ul3 = 4UL;

 

 

 

float

Single-precision

float f1 = 3.14f, f3 = 3.14F;

double

Double-precision

double d = 3.14;

bool

Boolean

bool b1 = true, b2 = false;

char

Unicode char

char c1 = 'e', c2 = '\0';

decimal

Decimal

decimal d1 = 3.14M, d2 = 7m;


The keywords for the C# predefined types are aliases for types defined within the System namespace. For example, int is represented under .NET by the System.Int32 type, and float by the System.Single type.

This underlying representation of the prebuilt types within C# is the same set of programmed types as for all other .NET languages. This means that although the simple types can be manipulated simply as values, we can also program them as class types with a well-defined public set of methods. It also makes combining our code with other .NET languages considerably more direct. One benefit is that we do not have to translate or modify types in order to have them recognized in the other language. A second benefit is that we can directly reference or extend types built in a different .NET language. The underlying System types are listed in Table 1.3.

Table 1.3 The Underlying System Types

C# Type

System Type

C# Type

System Type

sbyte

System.SByte

byte

System.Byte

short

System.Int16

ushort

System.UInt16

int

System.Int32

uint

System.UInt32

long

System.Int64

ulong

System.UInt64

float

System.Single

double

System.Double

char

System.Char

bool

System.Boolean

decimal

System.Decimal

 

 

object

System.Object

string

System.String


1.18.3 Arithmetic, Relational, and Conditional Operators

C# predefines a collection of arithmetic, relational, and conditional operators that can be applied to the built-in numeric types. The arithmetic operators are listed in Table 1.4, together with examples of their use; the relational operators are listed in Table 1.5, and the conditional operators in Table 1.6.

The binary numeric operators accept only operands of the same type. If an expression is made up of mixed operands, the types are implicitly promoted to the smallest common type. For example, the addition of a double and an int results in the promotion of the int to double. The double addition operator is then executed. The addition of an int and an unsigned int results in both operands being promoted to long and execution of the long addition operator.

Table 1.4 The C# Arithmetic Operators

Operator

Description

Usage

*

Multiplication

expr1 * expr2;

/

Division

expr1 / expr2;

%

Remainder

expr1 % expr2;

+

Addition

expr1 + expr2;

-

Subtraction

expr1 - expr2;

++

Increment by 1

++expr1; expr2++;

--

Decrement by 1

--expr1; expr2--;


The division of two integer values yields a whole number. Any remainder is truncated; there is no rounding. The remainder is accessed by the remainder operator (%):

5 / 3 evaluates to 1, while 5 % 3 evaluates to 2
5 / 4 evaluates to 1, while 5 % 4 evaluates to 1
5 / 5 evaluates to 1, while 5 % 5 evaluates to 0

Integral arithmetic can occur in either a checked or unchecked context. In a checked context, if the result of an operation is outside the range of the target type, an OverflowException is thrown. In an unchecked context, no error is reported.

Floating-point operations never throw exceptions. A division by zero, for example, results in either negative or positive infinity. Other invalid floating-point operations result in NAN (not a number).

The relational operators evaluate to the Boolean values false or true. We cannot mix operands of type bool and the arithmetic types, so relational operators do not support concatenation. For example, given three variables—a, b, and c—that are of type int, the compound inequality expression

// illegal
a != b != c;

is illegal because the int value of c is compared for inequality with the Boolean result of a != b.

Table 1.5 The C# Relational Operators

Operator

Description

Usage

<

Less than

expr1 < expr2;

>

Greater than

expr1 > expr2;

<=

Less than or equal to

expr1 <= expr2;

>=

Greater than or equal to

expr1 >= expr2;

==

Equality

expr1 == expr2;

!=

Inequality

expr1 != expr2;


Table 1.6 The C# Conditional Operators

Op

Description

Usage

!

Logical NOT

! expr1

||

Logical OR (short circuit)

expr1 || expr2;

&&

Logical AND (short circuit)

expr1 && expr2;

|

Logical OR (bool)—evaluate both sides

bool1 | bool2;

&

Logical AND (bool)—evaluate both sides

bool1 & bool2;

?:

Conditional

cond_expr ? expr1 : expr2;


The conditional operator takes the following general form:

 	expr
   ? execute_if_expr_is_true
   : execute_if_expr_is_false;

If expr evaluates to true, the expression following the question mark is evaluated. If expr evaluates to false, the expression following the colon is evaluated. Both branches must evaluate to the same type. Here is how we might use the conditional operator to print either a space or a comma followed by a space, depending on whether last_elem is true:

Console.Write( last_elem ? " " : ", " )

Because the result of an assignment operator (=) is the value assigned, we can concatenate multiple assignments. For example, the following assigns 1024 to both the val1 and the val2 objects:

// sets both to 1024
val1 = val2 = 1024; 

Compound assignment operators provide a shorthand notation for applying arithmetic operations when the object to be assigned is also being operated upon. For example, rather than writing

cnt = cnt + 2;

we typically write

// add 2 to the current value of cnt
cnt += 2; 

A compound assignment operator is associated with each arithmetic operator:

+=, -=, *=, /=, and %=.

When an object is being added to or subtracted from by 1, the C# programmer uses the increment and decrement operators:

cnt++; // add 1 to the current value of cnt
cnt--; // subtract 1 from the current value of cnt

Both operators have prefix and postfix versions. The prefix version returns the value after the operation. The postfix version returns the value before the operation. The value of the object is the same with either the prefix or the postfix version. The return value, however, is different.

1.18.4 Operator Precedence

There is one "gotcha" to the use of the built-in operators: When multiple operators are combined in a single expression, the order in which the expressions are evaluated is determined by a predefined precedence level for each operator. For example, the result of 5+2*10 is always 25 and never 70 because the multiplication operator has a higher precedence level than that of addition; as a result, in this expression 2 is always multiplied by 10 before the addition of 5.

We can override the built-in precedence level by placing parentheses around the operators we wish to be evaluated first. For example, (5+2)*10 evaluates to 70.

Here is the precedence order for the more common operators; each operator has a higher precedence than the operators under it. Operators on the same line have equal precedence. In the case of equal precedence, the order of evaluation is left to right:

Logical NOT (!)
Arithmetic *, /, and %
Arithmetic + and -
Relational <, >, <=, and >=
Relational == and !=
Logical AND (&& and &)
Logical OR (|| and |)
Assignment (=)

For example, consider the following statement:

if (textline = Console.ReadLine() != null) ... // error!

Our intention is to test whether textline is assigned an actual string or null. Unfortunately, the higher precedence of the inequality operator over that of the assignment operator causes a quite different evaluation. The subexpression

Console.ReadLine() != null

is evaluated first and results in either a true or false value. An attempt is then made to assign that Boolean value to textline. This is an error because there is no implicit conversion from bool to string.

To evaluate this expression correctly, we must make the evaluation order explicit by using parentheses:

if ((textline = Console.ReadLine()) != null) ... // OK!

1.18.5 Statements

C# supports four loop statements: while, for, foreach, and do-while. In addition, C# supports the conditional if and switch statements. These are all detailed in Tables 1.7, 1.8, and 1.9.

Table 1.7 The C# Loop Statements

Statement

Usage

while 
while ( ix < size ){
    iarray[ ix ] = ix;
    ix++;
} 
for 
for (int ix = 0; ix<size; ++ix)
   iarray[ ix ] = ix;
foreach 
foreach ( int val in iarray )
   Console.WriteLine( val );
do-while
int ix = 0;
do 
{
   iarray[ ix ] = ix;
   ++ix;
} 
while ( ix < size );

Table 1.8 The C# Conditional if Statements

Statement

Usage

if
if (usr_rsp=='N' || usr_rsp=='n')
   go_for_it = false;

if ( usr_guess == next_elem )
{ // begins statement block
   num_right++;
   got_it = true;
} // ends statement block
if-else
if ( num_tries == 1 )
   Console.WriteLine( " ... " );
else
if ( num_tries == 2 )
   Console.WriteLine( " ... " );
else
if ( num_tries == 3 )
   Console.WriteLine( " ... " );
else Console.WriteLine( " ... " );

Table 1.9 The C# switch Statements

Statement

Usage

switch
// equivalent to if-else-if clauses above
switch ( num_tries ) 
{
   case 1:
     Console.WriteLine( " ... " );
     break;

   case 2:
     Console.WriteLine( " ... " );
     break;

   case 3:
     Console.WriteLine( " ... " );
     break;

   default:
     Console.WriteLine( " ... " );
     break;
}

// can use string as well
switch ( user_response )
{
   case "yes":
     // do something
     goto case "maybe";

   case "no":
     // do something
     goto case "maybe";

   case "maybe":
     // do something
     break;

   default:
     // do something;
     break;
}

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