- 1 A First C# Program
- 2 Namespaces
- 3 Alternative Forms of the Main() Function
- 4 Making a Statement
- 5 Opening a Text File for Reading and Writing
- 6 Formatting Output
- 7 The string Type
- 8 Local Objects
- 9 Value and Reference Types
- 10 The C# Array
- 11 The new Expression
- 12 Garbage Collection
- 13 Dynamic Arrays: The ArrayList Collection Class
- 14 The Unified Type System
- 15 Jagged Arrays
- 16 The Hashtable Container
- 17 Exception Handling
- 18 A Basic Language Handbook for C#
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 chapterChapter 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 suffixfor example, 42u, 1024U. To indicate a literal value of type long, we add a lower- or uppercase L as a suffixfor 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 suffixesfor 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 variablesa, b, and cthat 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; } |