C# Coding Techniques

I wrote this article for novice who needs to grasp the concepts of "What's C# code?" and "How we can write code?". To read this article you must have an overview of the .NET Framework and Visual Studio.NET (VS. NET) if possible.

Introduction

Before we discuss any of C# basics concepts you must understand what a computer program is?

A computer program is not that black box that you can't understand; when we go further in the book you will understand the whole story. Computer program is a series of lines of code that actually do 2 things.

1- Store data (in many different ways as we will learn later)
2- Manipulate this data ( in many different ways too)

For example, Microsoft Word is a complex huge program that manipulates text data, I mean you write a lines of text in the page and you can change the colors, bold the text, copy and paste the text in your documents and many other operations. Another example, Adobe Photoshop is a complex application (program) that works with photos and pictures. Here the photo will be the program's data and the program will manipulate this data using its operation. Actually you can think of this operation as the lines of code that we will write to manipulate this data.
 
Important Note:   In the beginning you may think that programming is difficult and you also think that you don't understand anything. It's ok just wait until you finish the next 4 chapters and you will do fine because you will not grasp all the concepts in the same time.

C# Coding

As you learn another language French for example, you find it difficult in the beginning but when you go further and further you find that you are learning and life is easy. The same with C# writing code in the first will not be that easy but as you go further you will find yourself writing code without even looking for any reference. In this section and the next few you will learn many things about writing and organizing your code.

Keywords

Recall from chapter 1 when we said that every language consists of keywords and these keywords only understandable by the people who talk this language.

The same is here with C#, keywords are special words that have special meaning in the C# language and it's reserved by the language. Actually the last sentence means a lot but I'm afraid that you can't understand it now so I will take about it later.

Figure 2.1 display a table contains all the keywords in C#.
 

abstract event new struct
as explicit null switch
base extern object this
bool false operator throw
break finally out true
byte fixed override try
case float params typeof
catch for private uint
char foreach protected ulong
checked goto public unchecked
const if readonly unsafe
class implicit ref ushort
continue in return using
decimal int sbyte virtual
default interface sealed volatile
delegate  internal short void
do is sizeof while
double lock stackalloc
else long static 
enum namespace string


To explain what's a keyword let's go back to our language (English). Now when I write "Hello" actually it's a keyword in the English language and we tell it when we want to greet someone, so each of the keywords in figure 2.1 means something that you and the compiler will understand. So while we go further in the book you will learn more about these keywords and how to use them inside your code to form a program.

One of the VS. NET features is coloring the Keywords to the blue color so you can easily identify the keywords in C# code.

Identifiers

Identifiers are just names for your items; I mean for example, you are developing a program that contains an item which will add 2 numbers so you must give this item a number in your code so that name called identifier because it will identify your items.

I will give you many examples for identifiers later when appropriate. Now we must differentiate between Keywords and Identifiers. Keywords are special words reserved by the language and Identifiers are just names which you can use to call your items (I use the word 'items' because I suppose you don't know anything of C# building blocks like struct, class, method and like that) . So for example I can call my programming item "Michael" which is an item that can write to the screen "Hello I like programming in C#" so "Michael" here is an Identifier. I can't call this item "class", "int" or any of the words in Figure 2.1 because it's reserved by C# for special use.

When you name your items you must apply certain rules:

1. The first character in the name must start with a letter (uppercase or lowercase) or an underscore character "_" like the name "_myName".
2. The characters after the first one can be a digit, an underscore character, or a letter (uppercase or lowercase).

That's all what you need to know now about Keywords and Identifiers now.

C# Statements

Actually C# statement is the same as the English language complete sentence. This is the best and simplest analogy that illustrates what's a statement. Look at the following example:

I like Microsoft Products.

Anyone will read this sentence will understand that I like Microsoft Products but when I say:
I like

What? What do you like? This is what you may ask because it's not a complete sentence.

The same thing with C# statement, its form a complete instruction that C# compiler can understand so the next statement adds 2 numbers and stores it in the memory.

memory = 2 + 5;

Note that C# statements end with the semicolon ";"as the English sentence end with the full stop "." So you must put a semicolon as the end of each C# statement. In this last C# statement we told the compiler to put the result of adding these 2 numbers in the memory. Don't care about understanding the code right now because we have all the next chapters discussing C# coding.

You must know that C# programs consist of sequence of C# statements that execute in ascending order like the following example:

{
statement 1
statement 2
statement 3
}

The first statement (statement 1) will execute first then 2 and the end up with the last one (statement 3).

C# Building-Blocks

Whenever you write C# statement this statement will be part of a block called "Block of code" and actually it's much the same as paragraphs in English language which consists of a number of statements.

So they call it block because it's consists of related C# statements that will do the job that it's created for. C# Blocks may contain zero, one or many statements, these blocks must be delimited with curly brackets "{ }" like the following example:
 
{
int memory = 2 + 5;
Console.WriteLine(memory);
Console.WriteLine("so it's 7, right?");
}

This is a block of code that contains 3 statements, there are a number of important points that you must understand here:

1- int is a keyword and VS. NET colored it to the blue color so you can differentiate it.
2- There is a semicolon to end each of the 3 statements.
3- Each line contains only one statement.

You can have 2 statements in the same line and that's because C# compiler know that you end the statement with the ";". So you can write the last building block as following:

{
int memory =2 + 5;Console.WriteLine(memory);
Console.WriteLine("so it's 7,right?");
}

But by convention you have to write only one statement in the line so your code will appear in a better appearance and improve readability.

You can nest the blocks, I mean you can write one block inside the other look at the following block:

{
int memory = 2 + 5;
if(memory == 7)
{
Console.WriteLine("hi, I'm Michael");
}
}

Again don't look at the code and look at the blocks only, here we have 2 nested blocks of code. Just for now enough that you know that we can create blocks inside other blocks and later we will now how can that be useful.

Something important to note: When you write the left curly bracket "{" and write your code, then closing it with the right curly bracket "}" you will note that VS.NET will bold the whole block for a second and actually it's nothing more than a way to show you the contents of that block.

There are 3 more sections that will discuss code organization.

Commenting your code

While you are writing C# code you can write comments. A comment is just a text that you can write to explain or describe your code. For example, you have some block of code that add 2 numbers so you can use comments to describe the operation of this block of code like the following:

{
// This block of code will add 2 numbers and then put
// the result in the memory
int memory = 2 + 5;
}

Another feature of VS. NET is coloring the comments to green color text. You must know that you can write your comments using any language (English, French, or any other language) because C# compiler will ignore the comments. You can think of comments as something can live with C# code. In more complex blocks of code you will find that comments are very useful especially if you are reading other programmers code so their comments will help you understand many things.

There are 2 ways to write comments in C#. The first way is using the multi-line comments and the second way is using the single-line comments.

The multi-line comments begin with the characters "/*" and end with the characters "*/" as following:

/* this block of code will add 2 numbers
* and then put the result in the memory */

There are a few things that we must discuss here. This is a multi-line comment so you can press the Enter key after the opening characters "/*" and each time you press the enter key (for a new line) you will get a "*" character in the beginning of this new line.

The job of this character just to tell you that you have a new line in your comments, You can delete this character and complete writing your comments and when you finish you must close it with "*/" characters. When you close your multi-line comments VS. NET will bold all the text contained in your comments just to let you see how many lines and what's exactly the text that you wrote in your comments.

Important Note:   In the multi-line comments you can write anything except the closing character "*/" because VS. NET will think that you want to close the comments.

So you can't write the following:

/* the only special character that you can't write
* Inside the multi-line comments is the "*/
" character */

Here we wrote the closing characters as part of our multi-line comment so note that after the closing characters in the second line "*/" the text color is black and that's means it's anything but not a comment.

The single-line comments begin with the characters "//" and you can write your comments only at this line as the following:

// This block of code will add 2 numbers and then put
int memory = 2 + 5;

If you want to write more than one line in your comment then you must begin each line with "//" characters as following:

// This block of code will add 2 numbers and then put
// the result in the memory
int memory = 2 + 5;

You can write the single-line comment in the same line with your statement as the following:

int memory = 2 + 5; // this is a statement


There is a third way to comment your code but I prefer to not discuss it now. But you must know about it only. This kind of comments which you will find it In many kind of C# projects created by VS. NET begin by "///" characters:

/// <summary>
///
The main entry point for the application.
/// </summary>

You will find this kind of comments in C# projects created by VS. NET and it helps you to document your application.

Documentation is a help system developers create it so the application's users can learn how to use the application. So later we will give you overview of how to create documentation for your application using this kind of comment.

Some developers said that this is not a comment because you don't comment your code but you describe it. Anyway we will talk about it later.

Case-sensitivity and syntax errors

As we said before that C# is a case sensitive programming language, what that means? Let's see
In C# if you named an item "Michael" (with a capital "M") then it's not the same as "michael" and the C# compiler will not understand that Michael = michael and it will consider that they are 2 different items. So take care when giving names in your code.

In the program that write a line to the console.

using System;
namespace ConsoleApplication2
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Hello, I'm Michael");
}
}
}

I think now you know more about this code, you know that the blue words are keywords and the green lines are comments but let's talk about case-sensitive here.

All the keywords are made up of small letters and if you try to delete it and type it with any capital letter then the word color will not be blue and when you compile your program you will get an error. Later you will learn what's the things that you will write it in capital letters and what's the things that you must write it in small letters (by now, you know that keywords must be written in small letters).

I said that if you type "michael" instead of "Michael" (the item named with a capital "M") then the compiler will generate an error. This error called a syntax error.

In English language if you typed "noote" instead of "note" then it's a spelling error so you can understand the syntax error as the same as the English spelling error which will make the reader confused and stop reading. With C# the compiler will generate an error telling you about it (the error message will depend on the situation).

Syntax error is not just typing "michael" instead of "Michael" but it's a violation for the programming language coding rule, I mean that syntax errors is more than just a case sensitive for example, the next example is a syntax error:

{
Console.WriteLine("Hello");

We said before that C# blocks must delimited by "{" and "}" and here in this example we didn't close this block so it's a syntax error.

To avoid opening and closing problem of the blocks you can do the next:

1. If you want to create a block of code then type the opening and closing curly brackets in the same line like the following

{ }

2. Then press the enter key 2 times so you will have something like the following

{
}

3. Now you can write your code without worrying about the opening and closing curly brackets.

Another example for the syntax errors:
{
    Console.WriteLine("Hello")
}

In this example I didn't forget to close the block but I forget to put the semicolon at the end of the statement so it's also a syntax error and VS.NET will put a jagged line under the place of the syntax error (but sometimes I find that this jagged line confused because it may be in the next line of the error).

And there are many things that can make syntax errors occur but don't worry because we will learn about them. I explained syntax error here and before you learn more about C# for a couple of reason: the first reason is that the most common syntax error come from case-sensitive situation and the second because I want you to minimize your syntax error and focus on learning the language.

You must know that your program will not compile and executed until you fix all the syntax errors in the program. Actually VS. NET will help you tracking your syntax errors by providing an error message describing the error and also the jagged line that VS. NET will put under that line where the syntax error happened. Syntax errors also called compile-time error or compilation errors.

Next we will learn how we can organize our code as VS. NET does to improve readability.

Organizing code using Whitespace

To begin this section let's look at the following examples of a block of code
{
int x = 2 + 5 ; int y = x + 5;
Console.WriteLine(x); Console.WriteLine(y);
}

Now look at this one:
{
int x = 2 + 5;
int y = x + 5;
Console.WriteLine(x);
Console.WriteLine(y);
}

Both of these blocks will run and we will get the same result but the only difference between them is the Whitespaces inside our code.

Whitespaces are any white space inside your code like (space characters, tab characters, and carriage return characters (which is pressing the Enter key)). Programmers use Whitespace to make their code more readable and organized. In the 2 blocks above I used Whitespaces to write them but let's see the first one again:

{
int x = 2 + 5 ; int y = x + 5;
Console.WriteLine(x); Console.WriteLine(y);
}

Here there are many space characters between "2", "+" and '5". Also I wrote 2 statements in the second line.

Now let's look at the second block again:

{
int x = 2 + 5;
int y = x + 5;
Console.WriteLine(x);
Console.WriteLine(y);
}

It's organized block of code which contains 4 statements and there are 4 lines for them too. So use Whitespaces to organize your code and it make it more readable for you and for other developers.

We said that Whitespaces are (space, tab, carriage return characters) so if you look at the second (or the first) block of code you will find all of them. We used the tab character after the opening curly bracket "{"of the block to indent the body of the block then we used the enter key (carriage return) to move to the next line after writing the first statement and we used the space characters between the operators (=, +) and numbers (2, 5) to make our code look good.

As we said before that C# compiler ignores comments also C# compiler ignores Whitespaces and that's why both of blocks will run and get the same result so you can write the next block in 2 ways:

{int x = 2 + 5;}

Or you can write it as following:

{
int x = 2 + 5;
}

By convention, indent your block's body 1 tab character and take 1 space character between operators like (=, +, -, *) and numbers and take 1 carriage return character between statements.

VS. NET will help you indenting your blocks and if you want to see this do the next:

1. create a console application project and you will get the auto-generated code like this:

using System;
namespace testing
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
}
}
}

If you look at this code you will find that it's organized using the Whitespaces we discussed specially the tab character. So to create a block of code put your mouse cursor to the right of the red curly bracket "}" (actually I colored it red to just identify which one and VS. NET will not color it to red) and then press the Enter key to get a new line. Note that when you press Enter you will not get to the beginning of the next line but you will begin under the red curly bracket (I will tell you why later).

2. Write the next line of code

static void Michael()

And then press Enter also note here that VS. NET will not begin at the first of the next line but it will begin under the static keyword.

3. Now type the opening curly bracket "{"and press the enter key. VS. NET will indent the body of the block (1 tab character only) when you press the enter key to move to the next line and your mouse cursor will be positioned in place of the red l letter in the following code:

static void Michael()
{
    ..
    ..

So as we said VS. NET will help you indent your blocks and that's will save your time trying to organize your blocks. The same thing happens if you have 2 or more nested blocks of code. Look at the following block:

{
int x = 5;
if(x == 5)
{
Console.WriteLine(x);
}
}

This is a block which is contains another block of code. Note that the first statement in the outer block is indented 1 tab and the inner block is indented 1 tab too but the statement inside the inner block indented 1 tab of the inner block and so on.

Now we have a good overview of C# code and I hope that it was simple for you.

Up Next
    Ebook Download
    View all
    Learn
    View all