Basic C Syntax


Basic C# Syntax

The look and feel of C# code is similar to that of C++ and Java. At first, this syntax can look quite confusing and is a lot less like written English than some other languages. However, you will find as you immerse yourself in the world of C# programming that the style used is a sensible one, and it is possible to write very readable code without too much trouble.

Unlike the compilers of some other languages, C# compilers take no notice of additional spacing in code, whether made up of spaces, carriage returns, or tab characters (these characters are known collectively as white space characters). This means that you have a lot of freedom in the way that you format your code, although conforming to certain rules can help to make things easier to read.

C# code is made up of a series of statements, each of which is terminated with a semicolon. Since white space is ignored, you can have multiple statements on one line, but for readability's sake it is usual to add carriage returns after semicolons, so you don't have multiple statements on one line. It is perfectly acceptable (and quite normal), however, to use statements that span several lines of code.

C# is a block-structured language, meaning that all statements are part of a block of code. These blocks, which are delimited with curly brackets ({ and }), may contain any number of statements, or none at all. Note that the curly bracket characters do not need accompanying semicolons.

So, a simple block of C# code could take the following form:

 { <code line 1, statement 1>; <code line 2, statement 2> <code line 3, statement 2>; } 

Here, the <code line x, statement y> sections are not actual pieces of C# code; I've just used this text as a placeholder where C# statements would go. Note that in this case, the second and third lines of code are part of the same statement, because there is no semicolon after the second line.

In this simple section of code, I have also used indentation to clarify the C# itself. This isn't some random invention of mine, it is standard practice, and in fact VS will automatically do this for you by default. In general, each block of code has its own level of indentation, meaning how far to the right it is. Blocks of code may be nested inside each other (that is, blocks may contain other blocks), in which case nested blocks will be indented further:

 { <code line 1>; { <code line 2>; <code line 3>; } <code line 4>; } 

Also, lines of code that are continuations of previous lines are usually indented further as well, as in the third line of code in the first example above.

Note

If you look in the VS Options dialog, accessible via Tools Options, you can find the rules that VS uses for formatting your code. There are a whole lot of these, in subcategories of the Text Editor C# Formatting node. Most of the settings here reflect parts of C# that I haven't covered yet, but it can be worth returning to these settings later should you wish to tweak the settings to sort your personal style better. In this book, all code snippets are shown as they would be formatted by the default settings for clarity.

Remember, this kind of style is by no means mandatory. If you don't use it, however, you will quickly find that things can get very confusing as you move through this book!

Another thing you will often see in C# code is comments. A comment is not strictly speaking C# code at all, but happily cohabits with it. Comments do exactly what it says on the tin: they allow you to add descriptive text to your code — in plain English (or French, German, Outer Mongolian, and so on) — that will be ignored by the compiler. When you start dealing with lengthy sections of code, it can be useful to add reminders about exactly what you are doing, such as "this line of code asks the user for a number" or "this section of code was written by Bob." C# has two ways of doing this. You can either place markers at the beginning and end of a comment, or you can use a marker that means "everything on the rest of this line is a comment." This latter method is an exception to the rule mentioned above about C# compilers ignoring carriage returns, but it is a special case.

To mark out comments using the first method, you use /* characters at the start of the comment and */ characters at the end. These may occur on a single line, or on different lines, in which case all lines in between are part of the comment. The only thing you can't type in the body of a comment is */, because this is interpreted as the end marker. So, the following are OK:

 /* This is a comment */ /* And so... ... is this! */ 

But the following will cause problems:

 /* Comments often end with "*/" characters */ 

Here, the end of the comment (the characters after "*/") will be interpreted as C# code, and errors will occur.

The other commenting approach involves starting a comment with //. Next, you can write whatever you like — as long as you keep to one line! The following is OK:

 // This is a different sort of comment. 

But the following will fail, because the second line will be interpreted as C# code:

 // So is this, but this bit isn't. 

This sort of commenting is useful to document statements, because both can be placed on a single line:

 <A statement>;         // Explanation of statement 

Previously, I said that there were two ways of commenting C# code. However, there is a third type of comment in C# — although strictly speaking this is a development of the // syntax. You can use single- line comments that start with three / symbols instead of two, like this:

 /// A special comment 

Under normal circumstances, they are ignored by the compiler — just like other comments, but you can configure VS to extract the text after these comments and create a specially formatted text file when a project is compiled, which you can then use to create documentation. This is covered in detail in Chapter 28.

A very important point to note about C# code is that it is case-sensitive. Unlike some other languages, you must enter code using exactly the right case, because simply using an uppercase letter instead of a lower- case one will prevent a project from compiling.

This is difficult to illustrate without learning a bit more about the C# language, but take a look at this line of code, which is used in the first example in Chapter 2:

 Console.WriteLine("The first app in Beginning C# Programming!"); 

This code is understood by the C# compiler, as the casing of the Console.WriteLine() command is correct. However, none of the following lines of code will work:

 console.WriteLine("The first app in Beginning C# Programming!"); CONSOLE.WRITELINE("The first app in Beginning C# Programming!"); Console.Writeline("The first app in Beginning C# Programming!"); 

Here, the casing used is wrong, so the C# compiler won't know what you are trying to do.

Luckily, as you soon discover, VS is very helpful when it comes to entering code, and most of the time it knows (as much as a program can know) what you are trying to do. As you type, it suggests commands that you might like to use, and it tries as best it can to correct casing problems.

Basic C# Console Application Structure

Let's take a closer look at the console application example from Chapter 2 (ConsoleApplication1), and break down the structure a bit. The code was:

using System; using System.Collections.Generic; using System.Text;     namespace ConsoleApplication1 {    class Program    {       static void Main(string[] args)       {          // Output text to the screen.          Console.WriteLine("The first app in Beginning C# Programming!");          Console.ReadKey();       }    } }

You can immediately see that all the syntactic elements discussed in the last section are present here. There are semicolons, curly braces, and comments, along with appropriate indentation.

The most important section of code as far as you're concerned at the moment is the following:

static void Main(string[] args) {    // Output text to the screen.    Console.WriteLine("The first app in Beginning C# Programming!");    Console.ReadKey(); }

This is the code that is executed when you run your console application, or to be more precise, the code block enclosed in curly braces is what is executed. The comment line doesn't do anything, as mentioned earlier; it's just there for clarity. The other two code lines output some text to the console window and wait for a response, respectively, though the exact mechanisms of this shouldn't concern you for now.

At this point, it's worth noting how to achieve the code outlining functionality that was seen in the last chapter, albeit for a Windows application, since it is such a useful feature. You can do this with the #region and #endregion keywords, which define the start and end of a region of code that can be expanded and collapsed. For example, you could modify the generated code for ConsoleApplication1 as follows:

 #region Using directives     using System; using System.Collections.Generic; using System.Text;     #endregion 

This would allow you to collapse these lines of code into a single line, and expand it again later should you want to look at the details. the using statements contained here, and the namespace statement just underneath, will be explained at the end of this chapter.

Note

Note that any keyword that starts with a # is actually a preprocessor directive and not, strictly speaking, a C# keyword. Other than the two described here, #region and #endregion, these can be quite complicated, and have quite specialized uses. For that reason this is one subject you might like to investigate yourself once you have worked through this book.

For now, you shouldn't worry about the other code in the example, because the purpose of these first few chapters is to explain basic C# syntax, so the exact method of how the application execution gets to the point where Console.WriteLine() is called is of no concern. Later on, the significance of this additional code will be made clear.




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

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