C Syntax Fundamentals


C# Syntax Fundamentals

Once you successfully compile and run the HelloWorld program, you are ready to start dissecting the code to learn its individual parts. First, consider the C# keywords along with the identifiers that the developer chooses.

Beginner Topic: Keywords

In order for the compiler to interpret the code, certain words within C# have special status and meaning. Known as keywords or reserved words, they provide the concrete syntax that the compiler uses to interpret the expressions the programmer writes. In the HelloWorld program, class, static, and void are examples of keywords.

The compiler uses the keywords to identify the structure and organization of the code. Because the compiler interprets these words with elevated significance, you can use keywords only under the specific rules identified by the language. In other words, programming languages require that developers place keywords in only certain locations. When programmers violate these rules, the compiler will issue errors.


C# Keywords

Table 1.1 shows the C# keywords.

Table 1.1. C# Keywords

abstract

add*

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

get*

goto

if

implicit

in

int

interface

internal

is

lock

long

namespace

new

null

object

operator

out

override

params

partial*

private

protected

public

readonly

ref

remove*

return

sbyte

sealed

set*

short

sizeof

stackalloc

static

string

struct

switch

this

throw

true

try

typeof

uint

ulong

unchecked

unsafe

ushort

using

value*

virtual

void

volatile

where*

while

yield[a]

   


[a] Contextual keyword

C# 2.0 does not introduce any new keywords, but some C# 2.0 constructs use contextual keywords, which are significant only in certain locations. Outside these designated locations, contextual keywords have no special significance. [1.5] By this method, all C# 1.0 code is fully compatible with the C# 2.0 standard. [6] (Table 1.1 designates contextual keywords with an asterisk.)

[1.5] For example, early in the design of C# 2.0, the language designers designated yield as a keyword, and Microsoft released alpha versions of the C# 2.0 compiler, with yield as a designated keyword, to thousands of developers. However, the language designers eventually determined that by using yield return rather than yield, they could ultimately avoid adding yield as a keyword because it would have no special significance outside its proximity to return.

[6] There are some rare incompatibilities, such as C# 2.0 requiring implementation of IDisposable with the using statement, rather than simply a Dispose() method.

Beginner Topic: Identifiers

In addition to the keywords defined in C#, developers may provide their own names. Programming languages refer to these names as identifiers since they identify constructs that the programmer codes. In Listing 1.1, HelloWorld and Main are examples of identifiers. By assigning an identifier, it is possible to refer back to the same construct using the identifier. It is important, therefore, that the names the developer assigns are meaningful rather than arbitrary. A keen ability to select succinct and indicative names is an important characteristic of a strong programmer because the resulting code is easier to understand and reuse. In some rare cases, some identifiers, like Main, can have a special meaning in the C# language.


Type Definition

All code in C# appears within a type definition, and the most common type definition begins with the keyword class. A class definition is the section of code that begins with class <Identifier> { ... }, as shown in Listing 1.2.

Listing 1.2. Basic Class Declaration

class HelloWorld {   ... }

The name used for the type (in this case, HelloWorld) can vary, but by convention, it should begin with a capital letter. If the name contains multiple words appended together, then each additional word should also begin with a capital letter. For this particular example, therefore, other possible names are HelloWorld, HelloInigoMontoya, and simply Hello. The CLI creators called this type of casing Pascal casing because of its popularity in the Pascal programming language. The alternative, camel casing, follows the same convention, except that the first letter is lowercase. Examples include quotient, firstName, and theDreadPirateRoberts.

Generally, programs contain multiple types, each containing multiple methods.

Main

Beginner Topic: What Is a Method?

Syntactically, a method in C# is a named block of code introduced by a method declaration (e.g., static void Main()) and followed by zero or more statements within curly braces. Methods perform computations and/or actions. Similar to paragraphs in written languages, methods provide a means of structuring and organizing code so that it is more readable. More importantly, methods avoid the need to duplicate code. The method declaration introduces the method and defines the method name along with the data passed to and from the method. In Listing 1.3, Main() followed by { ... } is an example of a C# method.


The point where C# programs begin execution is the Main method, which begins with static void Main(). When you execute the program by typing HelloWorld.exe at the command console, the program starts up, resolves the location of Main, and begins executing the first statement (see Listing 1.3).

Listing 1.3. Breaking Apart HelloWorld

Although the Main method declaration can vary to some degree, static and the method name, Main, are always required.

Advanced Topic: Declaration of the Main Method

Although it is possible to declare the Main method without parameters or a return type, C# supports specifying either one. Listing 1.4 shows the full declaration of the Main method.

Listing 1.4. The Main Method, with Parameters and a Return

static int Main(string[] args) {     ... }

The args parameter is an array of strings corresponding to the command-line parameters. However, the first element of the array is not the program name but the first command-line parameter to appear after the executable name, unlike in C and C++. To retrieve the full command used to execute the program use System.Environment.CommandLine.

The int return from Main is the status code and it indicates the success of the program's execution. A return of a nonzero value generally indicates an error.


Language Contrast: C++/Javamain() Is All Lowercase

Unlike its C-style predecessors, C# uses an uppercase M for the Main method in order to be consistent with the Pascal-based naming conventions of C#.


The designation of the Main method as static indicates that other methods may call it directly off the class definition. Without the static designation, the command console that started the program would need to perform additional work (known as instantiation) before calling the method. (Chapter 5 contains an entire section devoted to the topic of static members.)

Placing void prior to Main() indicates that this method does not return any data (explained further in Chapter 2).

One distinctive C/C++ style characteristic followed by C# is the use of curly braces for the body of a construct, such as the class or the method. For example, the Main method contains curly braces that surround its implementation; in this case, only one statement appears in the method.

Statements and Statement Delimiters

The Main method includes a single statement, System.Console.WriteLine(), which is used to write a line of text to the console. C# generally uses a semicolon to indicate the end of a statement, where a statement comprises one or more actions that the code will perform. Declaring a variable, controlling the program flow, and calling a method are examples of statements.

Language Contrast: Visual BasicLine-Based Statements

Some languages are line based, meaning that without a special annotation, statements cannot span a line. Visual Basic is an example of a line-based language. It requires an underscore at the end of a line to indicate that a statement spans multiple lines.


Advanced Topic: Statements without Semicolons

It is only generally true that all statements in C# end with a semicolon. One example that does not include the semicolon is a switch statement. Because curly braces are always included in a switch statement, C# does not require a semicolon following the statement. In fact, code blocks themselves are considered statements (they are also composed of statements) and they don't require closure using a semicolon.


Since creation of a newline does not separate statements, you can place multiple statements on the same line and the C# compiler will interpret the line to have multiple instructions. For example, Listing 1.5 contains two statements on a single line that, in combination, display Up and Down on two separate lines.

Listing 1.5. Multiple Statements on One Line

System.Console.WriteLine("Up");System.Console.WriteLine("Down");

C# also allows the splitting of a statement across multiple lines. Again, the C# compiler looks for a semicolon to indicate the end of a statement (see Listing 1.6).

Listing 1.6. Splitting a Single Statement across Multiple Lines

System.Console.WriteLine(   "Hello. My name is Inigo Montoya.");

In Listing 1.6, the original WriteLine() statement from the HelloWorld program is split across multiple lines.

Whitespace

The semicolon makes it possible for the C# compiler to ignore whitespace in code. Apart from a few exceptions, C# allows developers to insert whitespace throughout the code without altering its semantic meaning. In Listing 1.5 and Listing 1.6, it didn't matter whether a newline was inserted within a statement or between statements, and doing so had no effect on the resulting executable created by the compiler.

Beginner Topic: What Is Whitespace?

Whitespace is the combination of one or more consecutive formatting characters such as tab, space, and newline characters. Eliminating all whitespace between words is obviously significant, as is whitespace within a quoted string.


Frequently, programmers use whitespace to indent code for greater readability. Consider the two variations on HelloWorld, as shown in Listing 1.7 and Listing 1.8.

Listing 1.7. No Indentation Formatting

class HelloWorld { static void Main() { System.Console.WriteLine("Hello Inigo Montoya"); } }

Listing 1.8. Removing Whitespace

class HelloWorld{static void Main() {System.Console.WriteLine("Hello Inigo Montoya");}}

Although these two examples look significantly different from the original program, the C# compiler sees them as identical.

Beginner Topic: Formatting Code with Whitespace

Indenting the code using whitespace is important for greater readability. As you begin writing code, you need to follow established coding standards and conventions in order to enhance code readability.

The convention used in this book is to place curly braces on their own line and to indent the code contained between the curly brace pair. If another curly brace pair appears within the first pair, all the code within the second set of braces is also indented.

This is not a uniform C# standard, but a stylistic preference.





Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net