Saturday, 6 October 2012

Using the IntelliSense

Perhaps one of the most important feature of the Visual Studio family is the IntelliSense. IntelliSense serves as an auto completion tool as well as a quick reference for classes, methods, and many more. I remember using an old IDE for C++ and I have to memorize the necessary codes I have to use. With IntelliSense, I learn as I type because you actually see a brief description of each components describing how to use them.
IntelliSense is activated the moment you type a letter in the Code Editor. Type the following code inside the Main method of the program.
System.Console.WriteLine("C# Tutorials!");
 
Typing the first letter of the statement automatically activates IntelliSense.












IntelliSense gives you a list of recommendations with the most relevant one on the first of the list. You can press tab to accept the selected recommendation. Typing a dot will bring you another list of recommendations. The list is based on all the components that are contained inside the preceding namespace. If you stay the selection for a short amount of time, the description about the selected item will show up. This allows you to learn what each item does without going to the full documentation.



As you type the code, the list is narrowed down. For example, typing the letter W make IntelliSense to only show items with W's in it.













Typing more letters will narrow the list even further.
If IntelliSense cannot find something that matches what you are typing, then nothing will be shown. You can press Ctrl while a list is shown to make the list transparent. It's useful when the list box is blocking some of your codes.



When working with methods with multiple overloads(versions), you can use the arrow heads to see all the possible overloads of the method.
You will also see the different parameters required by the method and their individual descriptions. Methods and parameters will be discussed in a later lesson.
IntelliSense is such a great feature, and for every release of Visual Studio, IntelliSense becomes even more intelligent in suggesting codes for you. It is one of the time-saving tools Visual Studio offers.

Friday, 5 October 2012

Creating a Simple Program

Let's create our very first program using the C# programming language. The program will print a line of message in the console window. Note that we will be using Console Application as the project type for the following tutorials. This is just an overview of what you will learn in the following lessons. I will explain here the structure and syntax of a simple C# program.


Open up Visual C# Express. Go to File > New Project to open the New Project Window. You will be presented with a window asking you of the type and name of project you want to create.






Choose Console Application as the project type and name it MyFirstProgram. A Console Application is a program that runs in command prompt(console) and has no visual or graphical interface. You will deal with this type of project because it will be easier to demonstrate the language concepts compared to using windows forms. We will begin with visual programming once we are finished with the fundamentals of this language.
After pressing OK, Visual C# Express will create a solution file in a temporary directory. A solution is a collection of projects but for most of the tutorials, solutions only contain 1 project. The solution file with file extension .sln contains details about the projects and files associated with it and many more. Creating a new project also creates a .csproj file which contains details about the project and its associated files.
Since we choosed Console Application as the project type, there will be no Designer. Instead, we are presented with the Code Editor.

 
The Code Editor is where you type your codes. Codes typed in the editor are color coded so it will be easier for you to recognize certain parts or components of your code. Color Coding is another great feature of the Visual Studio family. The combo box to the top left(1) will list all the classes, structures, enumerations, and delegates in the code and the combo box to the top right(2) will list all the members of the class, structure, or enumeration where the cursor is positioned inside. Don't worry about the terms I used, they will be discussed in later lessons.
A .cs file named Program.cs is created and is contained by the project. It will contain the codes for your program. All C# code files has .cs file extensions. You will be presented with a prewritten code to get you started, but for now, delete everything and replace it with the following code:

1
2
3
4
5
6
7
8
9
10
namespace MyFirstProgram
{
    class Program
    {                               
        static void Main()
        {
            System.Console.WriteLine("Welcome to Visual C# Tutorials!");
        }
     }
}
Example1: - A Simple C# Program
 
The numbers to the right are not part of the actual code. They are only there so it will be easier to reference which code is being discussed by simply telling their associated line number(s). In Visual C# Express, you can go to Tools > Options > Text Editor > C# and then check the Line Numbers check box to show line numbers in your Visual C# Express or Visual Studio code editor.

Structure of a C# Program

The code in Example 1 is the simplest program you can make in C#. It's purpose is to display a message to the console screen. It has a nice structure which is easy on the eyes compared to other programming languages. Every language has its own basic syntax, which are rules to follow when writing your code. Let's try to explain what each line of code does.
Line 1 is a namespace declaration, which declares a namespace used as containers for your codes and for avoiding name collisions. Namespaces will be covered in detail in another lesson. Right now, the namespace represents the name of your project. Line 2 is a { symbol which is called a curly brace. Curly braces defines a code block. C# is a block-structured language and each block can contain statements or more valid code blocks. Note that each opening curly brace ( { ) should have a matching closing brace ( } ) at the end. Everything inside the curly braces in Line 2 and 10 is the code block or body of the namespace.
Line 3 declares a new class. Classes are a topic of object oriented programming and you will learn everything about it in later lessons. For now, the codes you write should be contained inside a class. You can see that it also has its own pair of curly braces (Line 4 and 9), and everything between them is the class' code block.
Line 5 is called the Main method. A method encapsulates a code and then executes it when the method is called. Details in creating a method will be explained in a later lesson. The Main method is the starting point of the program. It means that it is the entry point of execution and everything inside the Main method are the first ones to execute after all the initializations have been completed. Picture the Main method as the front door of your house. You will learn more about the Main method in a later lesson. The Main method and other methods you will create also has a set of curly braces which defines its code block and inside it are the statements that will be executed when the method is called.
Statements are another term for a line of code in C#. Each statements must end with a semicolon (;). Forgetting to add the semicolon will result in a syntax error. Statements are located inside code blocks. An example of a statement is the following code (Line 7):
System.Console.WriteLine("Welcome to Visual C# Tutorials!");
This is the code that displays the message "Welcome to Visual C# Tutorials!". We need to use the WriteLine() method and pass the string message inside it. A string or string literal, is a group of characters and they are enclosed in double quotes ("). A character is any letter, number, symbol, or punctuation. For now, the whole line simply means "Use the WriteLine method located in the Console class which is located in the System namespace". More of these will be explained in the upcoming lessons.
C# ignores spaces and new lines. Therefore, you can write the same program in Example 1 in just one line. But that will make your code extremely hard to read and debug. Also keep in mind that statements don't necessarily need to be in one line. One common error in programming is adding semicolons at every end of a line even though multiple lines represent a single statement. Consider the following example.
System.Console.WriteLine(
    "Welcome to Visual C# Tutorials!");
 
Since C# ignores white space, the above snippet is acceptable. But the following is not.
System.Console.WriteLine( ;
    "Welcome to Visual C# Tutorials!");
 
Notice the semicolon at the end of first line. This will produce a systax error because the two lines of code are considered as one statement and you only add a semicolon at the end of a single statement. Some statements such as the if statement can have their own code blocks and you don't have to add semicolons at the end of each block.
Always remember that C# is a case-sensitive language. That means you must also remember the proper casing of the codes you type in your program. Some exceptions are string literals and comments which you will learn later. The following lines will not execute because of wrong casing.

system.console.writeline("Welcome to Visual C# Tutorials!");
SYSTEM.CONSOLE.WRITELINE("Welcome to Visual C# Tutorials!");
sYsTem.cONsoLe.wRItelIne("Welcome to Visual C# Tutorials!");
 
 
Changing the casing of a string literal doesn't prevent the code from running. The following is totally okay and has no errors.
System.Console.WriteLine("WELCOME TO VISUAL C# TUTORIALS!");
But what will be displayed is exectly what you have indicated in the string literal.
Also notice the use of indention. Everytime you enter a new block, the codes inside it are indented by 1 level.
{
    statement1;
}
This makes your code more pleasing to the eyes because you can easily determine which code belongs to which block. Although it is optional, it is highly recommended to use this practice. One great feature of Visual C# Express and Visual Studio is its auto-indent feature so you don't have to worry about indention when entering new blocks.

Saving Your Project and Solution

To save your project and solution, you can go to File > Save All or use the shortcut Ctrl+Shift+S. You can also access this command in the toolbar. It is represented by multiple diskettes.

You will then be prompted with Save Project Window.

 
The Name field will already be filled with the Name you provided when you created the project. The Location field specifies where you want to save the project. Click the Browse button to select a location in your disk. The Solution Name field specifies the name for the solution. Leave the checkbox checked so VCE will create a folder for your solution located on the specified path in the Location field. Click Save to finish saving.
If you simply want to save a single file, go to File > Save (FileName) where FileName is the name of the file to be saved. You can use the shortcut Ctrl+S or click the single diskette icon in the toolbar beside the Save All icon.
To open a project or solution file, go to File > Open, or find the folder icon in the toolbar right before the save icon. Browse for the project of solution file. A solution file has an extension name of .sln and a project file has an extension name of .csproj. When opening a solution file, all the linked project to that solution will be opened as well together with the files associated for each of the projects.

Compiling the Program

We learned that our code needs to be compiled first to Microsoft Intermediate Language before we can run it. To compile our program, go to Debug > Build Solution or simply hit F6. This will compile all the projects within the solution. To build a single project, go to the Solution Explorer and right click a project, then select Build.

Rebuild simply recompiles a solution or project. I will not require you to always build the project if you will simply run the program because executing the program (as described next) automatically compiles the project.
You can now find the executable program of your project with .exe extension. To find this, go to the solution folder at the location you specified when you saved the solution/project. You will find here another folder for the project, and inside, find the folder named bin, then enter the Release folder. There you will finally find the executable file. (If you can't find it in the Release folder, try the Debug folder).

Executing the Program

When we execute a program, Visual C# Express automatically compiles our code to Intermediate Language. There are modes of executing/running a program, the Debug Mode and the Non-Debug Mode.
The Non-Debug Mode runs or executes the program disabling the debugging features of the IDE. The program will be executed the same way it will be executed when it is run by the user who will use your program. By running the program in Non-Debug mode you will be prompted to enter any key to continue once the program reaches the end. By default, the command for running in Non-Debug Mode is hidden if you are using the Basic Settings. We need to switch to Expert Settings to expose more options in the menu. Go to Tools > Settings then check Expert Settings. Wait for the IDE to finish adjusting settings. You can now run in Non-Debug mode by going to Debug > Start Without Debugging in the menu bar. You can also use the shortcut Ctrl+F5. You will get the following output:

Welcome to Visual C# Tutorials!
Press any key to continue . . .
 
Note that the message "Press any key to continue..." is not part of the actual output. This will only show if you run your program in Non-Debug mode. It is only there to prompt you to press any key to exit or continue the program.

The Debug Mode is easier to access and is the default for running programs in Visual C# Express. This mode is used for debugging(testing for errors) which will be discussed in a future lesson. You will be able to use break points and helper tools when exceptions are encountered when your program is running. Therefore, I recommend you to use this mode when you want to find errors in your program during runtime. To run using Debug Mode, you can go to Debug > Start Debugging or simply hit F5. Alternatively, you can click the green play button located at the toolbar.

 
Using Debug Mode, you program will show and immediately disappear. This is because during Debug Mode, once the program reaches the end of code, it will automatically exit. To prevent that from happening, you can use the System.Console.ReadKey() method as a workaround which stops the program and asks the user for an input. (Methods will be discussed in detail in a later lesson.)

namespace MyFirstProgram
{
    class Program
    {
        static void Main()
        {
             System.Console.WriteLine("Welcome to Visual C# Tutorials!");
             System.Console.ReadKey();
        }
    }
}
 
Example 2: - Using the Console.ReadKey() Method
 
Now run the program again in Debug Mode. The program will now pause to accept an input from you, simply hit Enter to continue or exit the program. I would recommend to use the Non-Debug mode just so we don't need to add the additional Console.ReadKey() code at the end. From now on, whenever I say run the program, I will be assuming that you use the Non-Debug mode unless otherwise noted. We will use Debug mode when we reach the topic of Exception Handling.

Importing Namespaces

Namespaces in a nutshell are container of codes that you can use in a program. We defined our own namespace named MyFirstProgram but there are thousands of namespaces inside the .NET Framework Class Library. An example is the System namespace which contains codes that are essential for a basic C# application. The Console class we are using to print lines is actually inside the System namespace. We are using the fully qualified name of the Console class which includes the namespace System throughout this lesson.

System.Console.WriteLine("Welcome to Visual C# Tutorials!");
System.Console.ReadKey();

This can be tedious if you will be repeatedly typing this over and over. Fortunately, we can import namespaces. We can use using statements to import a namespace. Here's the syntax:
using namespace;
 
This is an example of a using statement which imports a namespace and instructs the whole program that you are using the contents of that namespace. So instead of using the following line of code:
System.Console.WriteLine("Hello World!");
 
We can simply write the following code when we imported the System namespace:
Console.WriteLine("Hello World");
 
Using statements which imports namespaces are typically placed at the topmost part of your code. Here is the updated version of Example 2 which imports the System namespace.

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main()
        {
             Console.WriteLine("Welcome to Visual C# Tutorials!"); 
             Console.ReadKey();                                    
        }
    }
}
 
Example 3: - Importing a Namespace
You can still use the full name of a class though if there are other class which has the same name. Namespaces will be discussed in greater detail in another lesson.
You are now familiar with the workflow of creating as well as the basic structure and syntax of a simple C# program.