Chapter 2. Syntax of the C# Language

C# has all the features of any powerful, modern language. If you are familiar with Java, C, or C++, you’ll find most of C#’s syntax very familiar. If you have been working in Visual Basic or related areas, you should read this chapter to see how C# differs from VB. You’ll quickly see that every major operation you can carry out in Visual Basic.NET has a similar operation in C#.

The two major differences between C# and Visual Basic are (1) C# is case sensitive (most of its syntax is written in lowercase), and (2) every statement in C# is terminated with a semicolon (;). Thus, C# statements are not constrained to a single line, and there is no line continuation character.

In Visual Basic, we could write the following.


y = m * x + b       'compute y for given x

Or we could write this.


Y = M * X + b       'compute y for given x

Both would be treated as the same. The variables Y, M, and X are the same whether written in upper- or lowercase. In C#, however, case is significant, and if we write this


y = m * x + b;             //all lowercase

or this


Y = m * x + b;             //Y differs from y

we mean two different variables: Y and y. While this may seem awkward at first, you should find that it is helpful to be able to use case to make distinctions. For example, programmers often capitalize symbols that refer to constants.


Const PI = 3.1416 As Single in VB
const float PI = 3.1416;    // in C#

The const modifier in C# means that the named value is a constant and cannot be modified.

Programmers also sometimes define data types with mixed case and variables of that data type with lowercase.


class Temperature {       //begin definition of
                          //new data type
Temperature temp;         //temp is of this new type

We’ll cover classes in much more detail in the chapters that follow.

Data Types

The major data types in C# are shown in Table 2-1. Note that the lengths of these basic types are not related to the computer type or operating system. Characters and strings in C# are always 16 bits wide to allow for representation of characters in non-Latin languages. It uses a character coding system called Unicode, in which thousands of characters for most major written languages have been defined. You can convert between variable types in the usual ways.

Table 2-1. Data Types in C#

image

Any wider data type can have a narrower data type (having fewer bytes) assigned directly to it, and the promotion to the new type will occur automatically. If y is of type float and j is of type int, then you can promote an integer to a float in the following way.


float y = 7.0f;       //y is of type float
int j = 5;            //j is of type int
y = j;                //convert int to float

• You can reduce a wider type (more bytes) to a narrower type by casting it. You do this by enclosing the data type name in parentheses and putting it in front of the value you wish to convert.


j = (int)y;           //convert float to integer

You can also write legal statements that contain casts that might fail.


float x = 1.0E45;
int k = (int) x;

If the cast fails, an exception error will occur when the program is executed.

Boolean variables can only take on the values represented by the reserved words true and false. Boolean variables also commonly receive values as a result of comparisons and other logical operations.


int k;
boolean gtnum;

gtnum = (k > 6);     //true if k is greater than 6

Unlike C or C++, you cannot assign numeric values to a Boolean variable and you cannot convert between Boolean and any other type.

Converting between Numbers and Strings

To make a string from a number or a number from a string, you can use the Convert methods. You can usually find the right one by simply typing “Convert” and a dot in the development environment, and the system will provide you with a list of likely methods.


string s = Convert.ToString (x);
float y = Convert.ToSingle (s);

Note that “Single” means a single-precision floating point number.

Numeric objects also provide various kinds of formatting options to specify the number of decimal places.


float x = 12.341514325f;
string s = x.ToString ("###.###");         //gives 12.342

Declaring Multiple Variables

You should note that in C# you can declare a number of variables of the same type in a single statement.


int i, j;
float x, y, z;

This is unlike VB6, where you had to specify the type of each variable as you declare it.


Dim i As Integer, j As Integer
Dim x As Single, y As Single, z As Single

Many programmers find, however, that it is clearer to declare each variable on a single line so they can comment on each one specifically.


int i;         //used as an outer loop index
int j;         //the index for the y variables
float x;       //the ordinate variable

Numeric Constants

Any number you type into your program is automatically of type int if it has no fractional part or type double if it does. If you want to indicate that it is a different type, you can use various suffix and prefix characters.


float loan = 1.23f;       //float
long pig   = 45L;         //long
int color = 0x12345;      //hexadecimal

C# also has three reserved word constants: true, false, and null, where null means an object variable that does not yet refer to any object. We’ll learn more about objects in the following chapters.

Character Constants

You can represent individual characters by enclosing them in single quotes.


char c = 'q';

C# follows the C convention that white space characters (nonprinting characters that cause the printing position to change) can be represented by preceding special characters with a backslash, as shown in Table 2-2. Since in this case the backslash itself is a special character, it can be represented by using a double backslash.

Table 2-2. Representations of White Space and Special Characters

image

Variables

Variable names in C# can be of any length and can be of any combination of upper- and lowercase letters and numbers, but, like VB, the first character must be a letter. Note that since case is significant in C#, the following variable names all refer to different variables.


temperature
Temperature
TEMPERATURE

You must declare all C# variables that you use in a program before you use them.


int j;
float temperature;
boolean quit;

Declaring Variables as You Use Them

C# also allows you to declare variables just as you need them, rather than requiring that they be declared at the top of a procedure.


int k = 5;
float x = k + 3 * y;

This is very common in the object-oriented programming style, where we might declare a variable inside a loop that has no existence or scope outside that local spot in the program.

Multiple Equal Signs for Initialization

C#, like C, allows you to initialize a series of variables to the same value in a single statement.


i = j = k = 0;

This can be confusing, so don’t overuse this feature. The compiler will generate the same code for


i = 0; j = 0; k = 0;

whether the statements are on the same or successive lines.

A Simple C# Program

Now let’s look at a very simple C# program for adding two numbers together. This program is a stand-alone program, or application.


using System;
class add2
       {
             static void Main(string[] args)
             {
                   double a, b, c;  //declare variables
                   a = 1.75;        //assign values
                   b = 3.46;
                   c = a + b;       //add together
                   //print out sum
                   Console.WriteLine ("sum = " + c);
             }
       }

This is a complete program as it stands, and if you compile it with the C# compiler and run it, it will print out the result.


sum = 5.21

Let’s see what observations we can make about this simple program.

  1. You must use the using statement to define libraries of C# code that you want to use in your program. This is similar to the imports statement in VB and the import statement in Java. It is also similar to the C and C++ #include directive.
  2. The program starts from a function called Main, and it must have exactly the following form.


    static void Main(string[] args)

  3. Every program module must contain one or more classes.
  4. The class and each function within the class is surrounded by braces { }.
  5. Every variable must be declared by type before or by the time it is used. You could just as well have written the following.


    double a = 1.75;
    double b = 3.46;
    double c = a + b;

  6. Every statement must terminate with a semicolon. Statements can go on for several lines, but they must terminate with the semicolon.
  7. Comments start with // and terminate at the end of the line.
  8. Like most other languages (except Pascal), the equal sign is used to represent assignment of data.
  9. You can use the + sign to combine two strings. The string “sum =” is concatenated, with the string automatically converted from the double precision variable c.
  10. The writeLine function, which is a member of the Console class in the System namespace, can be used to print values on the screen.

This simple program is called add2.cs. You can compile and execute it in the development environment by just pressing F5.

Arithmetic Operators

The fundamental operators in C# are much the same as they are in most other modern languages. Table 2-3 lists the fundamental operators in C#.

The bitwise and logical operators are derived from C (see Table 2-4). Bitwise operators operate on individual bits of two words, producing a result based on an AND, OR or NOT operation. These are distinct from the Boolean operators because they operate on a logical condition that evaluates to true or false.

Table 2-3. C# Arithmetic Operators

image

Table 2-4. Logical Operators in C#

image

Increment and Decrement Operators

Like Java and C/C++ , C# allows you to express incrementing and decrementing of integer variables using the ++ and – – operators. You can apply these to the variable before or after you use it.


i = 5;
j = 10;
x = i++;       //x = 5, then i = 6
y = --j;       //y = 9 and j = 9
z = ++i;       //z = 7 and i = 7

Combining Arithmetic and Assignment Statements

C# allows you to combine addition, subtraction, multiplication, and division with the assignment of the result to a new variable.


x = x + 3;          //can also be written as:
x += 3;             //add 3 to x; store result in x

//also with the other basic operations:
temp *= 1.80;       //mult temp by 1.80
z -= 7;             //subtract 7 from z
y /= 1.3;           //divide y by 1.3

This is used primarily to save typing; it is unlikely to generate any different code. Of course, these compound operators (as well as the ++ and – – operators) cannot have spaces between them.

Making Decisions in C#

The familiar if-then-else of Visual Basic, Pascal, and Fortran has its analog in C#. Note that in C#, however, we do not use the then keyword.


if ( y > 0 )
  z = x / y;

Parentheses around the condition are required in C#. This format can be somewhat deceptive. As written, only the single statement following the if is operated on by the if statement. If you want to have several statements as part of the condition, you must enclose them in braces.


if ( y > 0 )
  {
  z = x / y;
  Console.writeLine("z =  " + z);
  }

By contrast, if you write


if ( y > 0 )
  z = x / y;
  Console.writeLine("z =  " + z);

the C# program will always print out z= and some number because the if clause only operates on the single statement that follows. As you can see, indenting does not affect the program; it does what you say, not what you mean.

For this reason, we generally advise enclosing all if statements in braces, even when they refer to only a single line.


if ( y > 0 )
{
  z = x / y;
}

If you want to carry out either one set of statements or another depending on a single condition, you should use the else clause along with the if statement.


if ( y > 0 )
{
  z = x / y;
}
else
{
  z = 0;
}

If the else clause contains multiple statements, they must be enclosed in braces, as in the preceding code.

There are two accepted indentation styles for braces in C# programs. This is one.


if (y >0 )
      {
      z = x / y;
      }

The other style, popular among C programmers, places the brace at the end of the if statement and the ending brace directly under the if.


if ( y > 0 ) {
  z = x / y;
  Console.writeLine("z=" + z);
}

You will see both styles widely used, and, of course, they compile to produce the same result.

You can set options in Visual Studio.NET to select which formatting method to use. In the Tools | Options menu, select the Text editor | C# folder and select formatting. Check the box marked “Leave open braces” on the same line as construct if you want the second style above, and leave it unchecked if you want the first style.

Comparison Operators

Previously, we used the > operator to mean “greater than.” Most of these operators are the same in C# as they are in C and other languages. In Table 2-5, note particularly that “is equal to” requires two equal signs and that “is not equal to” is different from in FORTRAN or VB.

Table 2-5. Comparison Operators in C#

image

Combining Conditions

When you need to combine two or more conditions in a single if or other logical statement, you use the symbols for the logical and, or, and not operators (see Table 2-6). T hese are totally different from any other languages except C/C++ and are confusingly like the bitwise operators shown in Table 2-6.

So, while we would write the following in VB.Net


If ( 0 < x) And (x <= 24) Then
  Console.writeLine ("Time is up")

we would write this in C#


if ( (0 < x) && ( x <= 24) )
  Console.writeLine("Time is up");

Table 2-6. Boolean Operators in C#

image

The Most Common Mistake

Since the is equal to operator is == and the assignment operator is =, they can easily be used incorrectly. If you write


if (x = 0)
  Console.writeLine("x is zero");

instead of


if (x == 0)
  Console.writeLine("x is zero");

you will get the confusing compilation error “Cannot implicitly convert double to bool” because the result of the fragment


(x = 0)

is the double precision number 0 rather than a Boolean true or false. Of course, the result of the fragment


(x == 0)

is indeed a Boolean quantity, and the compiler does not print any error message.

The Switch Statement

The switch statement allows you to provide a list of possible values for a variable and code to execute if each is true. In C#, however, the variable you compare in a switch statement must be either an integer, a character, or a string type and must be enclosed in parentheses.


switch ( j ) {
  case 12:
    System.out.println("Noon");
    break;
  case 13:
    System.out.println("1 PM");     "
    break;
  default:
    System.out.println("some other time...");
}

Note particularly that a break statement must follow each case in the switch statement. This is very important, since it says “go to the end of the switch statement.” If you leave out the break statement, a compilation error occurs.

If control can be transferred to the end of the switch statement without a match being found, an error occurs. You must provide a default case for all switch statements.

C# Comments

As you have already seen, comments in C# start with a double forward slash and continue to the end of the current line. C# also recognizes C-style comments, which begin with /* and continue through any number of lines until the */ symbols are found.


//C# single-line comment
/*other C# comment style*/
/* also can go on
for any number of lines*/

You cannot nest C# comments. Once a comment begins in one style, it continues until that style concludes.

When you are learning a new language, your initial reaction may be to ignore comments, but those at the beginning are just as important as later ones. A program never gets commented at all unless you do it as you write it, and if you ever want to use that code again, you’ll be glad to have some comments that help you decipher what you meant for it to do. For this reason, many programming instructors refuse to accept programs that are not thoroughly commented.

The Ornery Ternary Operator

C# has unfortunately inherited one of C/C++’s and Java’s most opaque constructions: the ternary operator. This statement


if ( a > b )
  z = a;
else
  z = b;

can be written extremely compactly as


z = (a > b) ? a : b;

Like the postincrement operators, this statement was originally introduced into the C language to give hints to the compiler so it would produce more efficient code and to reduce typing when terminals were very slow. Today, modern compilers produce identical code for both forms just shown, and the necessity for this turgidity is long gone. Some C programmers coming to C# consider this an “elegant” abbreviation, but we don’t, and we do not use it in this book.

Looping Statements in C#

C# has four looping statements: while, do-while, for, and foreach. Each of them provides a way to specify that a group of statements should be executed until some condition is satisfied.

The While Loop

The while loop is easy to understand. All of the statements inside the braces are executed as long as the condition is true.


i = 0;
while ( i < 100)
  {
   x = x + i++;
  }

Since the loop is executed as long as the condition is true, it is possible that such a loop may never be executed at all, and, of course, if you are not careful, that such a while loop will never be completed.

The Do-While Statement

The C# do-while statement is quite analogous, except in this case the loop must always be executed at least once, since the test is at the bottom of the loop.


i = 0;
do  {
   x += i++;
}
while (i < 100);

The For Loop

The for loop is the most structured. It has three parts: an initializer, a condition, and an operation that takes place each time through the loop. Each of these sections are separated by semicolons.


for (i = 0; i< 100; i++)  {
   x += i;
  }

Let’s take this statement apart.


for (i = 0;         //initialize i to 0
   i < 100 ;        //continue as long as i < 100
   i++)             //increment i after every pass

In the preceding loop, i starts the first pass through the loop set to zero. A test is made to make sure that i is less than 100, and then the loop is executed. After the execution of the loop, the program returns to the top, increments i, and again tests to see if it is less than 100. If it is, the loop is again executed.

Note that this for loop carries out exactly the same operations as the while loop illustrated previously. It may never be executed, and it is possible to write a for loop that never exits.

Declaring Variables as Needed in For Loops

One very common place to declare variables on the spot is when you need an iterator variable for a for loop. You can simply declare that variable right in the for statement, as in the following.


for (int i = 0; i < 100; i++)

Such a loop variable exists, or has scope, only within the loop. It vanishes once the loop is complete. This is important because any attempt to reference such a variable once the loop is complete will lead to a compiler error message. The following code is incorrect.


for (int i =0; i< 5; i++) {
   x[i] = i;
}

//the following statement is in error
//because i is now out of scope
System.out.println("i=" + i);

Commas in For Loop Statements

You can initialize more than one variable in the initializer section of the C# for statement, and you can carry out more than one operation in the operation section of the statement. You separate these statements with commas.


for (x=0, y= 0, i =0; i < 100; i++, y +=2)
  {
   x = i + y;
  }

It has no effect on the loop’s efficiency, and it is far clearer to write.


x = 0;
y = 0;
for ( i = 0; i < 100; i++)
  {
  x = i + y;
  y += 2;
  }

It is possible to write entire programs inside an overstuffed for statement, using these comma operators, but this is only a way of obfuscating the intent of your program.

How C# Differs from C

If you have been exposed to C or if you are an experienced C programmer, you might be interested in the main differences between C# and C.

  1. C# does not usually make use of pointers. You can only increment or decrement a variable as if it were an actual memory pointer inside a special unsafe block.
  2. You can declare variables anywhere inside a method that you want. They don’t have to be at the beginning of the method.
  3. You don’t have to declare an object before you use it. You can define it just as you need it.
  4. C# has a somewhat different definition of the struct types, and it does not support the idea of a union at all.
  5. C# has enumerated types that allow a series of named values, such as colors or days of the week, to be assigned sequential numbers, but the syntax is rather different.
  6. C# does not have bitfields, that is, variables that take up less than a byte of storage.
  7. C# does not allow variable-length argument lists. You have to define a method for each number and type of argument. However, C# allows for the last argument of a function to be a variable parameter array.
  8. C# introduces the ideas of delegates and indexers that are not present in any of the other common languages.

How C# Differs from Java

C# and Java are clearly close cousins, and since C# was designed after Java, it uses most of its best ideas. There are a few subtle differences.

  1. Many system object methods such as string have identical method names, differing only in capitalization.
  2. C# does not provide the throws keyword that allows the compiler to detect that you must catch the exception that might be thrown by a method.
  3. C# has a much more limited concept of layout managers. Since it is Windows-centric, it assumes absolute placement of graphical elements most of the time.
  4. C# allows operator overloading.
  5. C# introduces delegates and indexers.
  6. C# has enumerated types.
  7. C# has an unsafe mode, where it allows you to use pointers.
  8. You must specifically declare that a method can be overridden and that a method overrides another one.
  9. You cannot distinguish inheritance from implementing an interface from the declaration; they are both declared the same way.
  10. The switch statement allows string variables. If there is no specific match, there must be a default case or an error will occur. The break statement is required.
  11. The Boolean variable type is spelled “bool” in C# and “boolean” in Java.

Summary

In this brief chapter, we have seen the fundamental syntax elements of the C# language. Now that we understand the tools, we need to see how to use them. In the chapters that follow, we’ll take up objects and show how to use them and how powerful they can be.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset