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.

Exploring Visual C# Express 2010

Visual C# Express has lots of windows and components  that provides functionality or displays certain informations. Let's further explore the different parts of Visual C# Express by going deeper into the IDE. Create a new Windows Forms Application by going to File > New Project or using the shortcut Ctrl+Shift+N.
You will be presented with the New Project Window.





 
 
 
 



To the left is a list of categories of installed templates. Since you are using Visual C# Express, only C# is available. The center of the window shows the installed template for the specified category. Templates are precreated project files which are provided to you so you will not create them from scratch. All you have to do is create a project from a template and start programming. The number of templates listed varies depending on the templates installed in your computer. You can sort the name of the templates by ascending or descending order by using the combo box(drop down box) found at the top center. You can change the view of the templates by clicking the buttons next to that combo box. The right side shows a search box for searching installed templates and the description of the selected template. Choose Windows Forms Application from the list of templates. You can name your project using the text box found at the bottom. For now, leave it as it is.  Click OK to generate a project from the selected template.

Figure 1 - Newly created Windows Forms Application Project

 

The Designer.

 
 
The (1)Designer is like your canvas or drawing area for designing windows forms. Windows forms are graphical user interfaces and you see them everywhere when you use computers. You add controls to the form such as buttons, text boxes, labels, and many more. A more detailed look at windows forms, controls, and visual programming is located at the Windows Forms Section of this site. But it is recommended to finish the basic and fundamental lessons first before creating windows forms application.

 

The Solution Explorer.



The (2)Solutions Explorer shows the different projects and the files associated with the solution.  A solution represents the application you are creating. It may compose of a single project, or multiple projects, and each project is composed of files such as source code files and images. When you create a project, a solution is automatically created containing the project you have chosen. If the Solution Explorer is not visible, go to View > Other Windows > Solution Explorer or you can use the shortcut Ctrl+Alt+L. If multiple projects are present, the project in bold text is considered the Startup Project which is considered as the default project and the one that will run when you start debugging (more on this later). If the project you want to execute is not the startup project, right click the project in the Solution Explorer and then choose "Set as StartUp Project". Below is the Solution Explorer showing a Solution with 2 Projects. Each project contains files and folders associated to them.

The first button in its top bar allows you to edit the properties of the project. Some files located in the project directory are hidden in the Solution Explorer. You can click the second button to show all the hidden files.The third button refreshes the Solution Explorer in case files are added, deleted or modified. More buttons will show up depending on the current project or view you are working on. You can double click the files in the solution explorer to open them up or check their contents. You can also click the arrows to the left of each node to reveal child nodes they contain.

 

The Properties Window



The (3)Properties Window shows the different properties or events of any selected item such as files, projects, the form, or controls. If it is not visible to you, go to View > Other Windows > Properties Window or use the shortcut F4.
Properties can be considered as characteristics or attributes of objects. For example, a car has properties color, speed, size, and brand. If you are selecting a form or control in the Design View, or projects or files in the Solution Explorer, the Properties Window will show the properties available for them.
The Properties Window also allows you to view the events of a selected control or form. An event is something that happens when certain conditions occur such as when a button is clicked or when the text inside the text box is modified.
The top combo box(A) allows you to choose the object whose properties will be shown in the Properties Window. This is useful when you can't select certain controls(probably because of their small size) in the Designer. Below the combo box shows some helpful buttons(B). Some buttons only appear on certain instances. The first button will arrange the properties in different categories. The second button will arrange the properties in alphabetical order. I recommend pressing this button as I found it easier to find the properties you want when it is alphabetized. The third and fourth buttons only appear when you are selecting a control or a form in the designer view. The third button allows you to view the available properties of the current selected control or form. The fourth button (indicated by the thunder bolt icon) shows the available events for the selected control or form. The bottom box shows the description of the selected property or event.
The main part of the properties window(C) contains the properties or the events. The left column specifies names of the properties or event. The right column shows the values of the properties and events. There are simple properties that require a single value, but there are also complex properties that consist of more properties. These can be identified with an arrow on the left of those properties. If you click that arrow, subproperties of the property are shown. Some properties opens up special tools or windows when normal text input cannot be accepted. The bottom part of the Properties Window is the Description Box(D) which shows the description of functionality of the selected property or event.

Thursday 4 October 2012

Registering Visual C# Express 2010

Step 1:
Visual C# Express is free, but you need to register the product to be able to use it permanently. You need to obtain a key from Microsoft to activate your copy of Visual C# Express. Note that this key will be given to you for free after following the steps in this lesson.
Open Visual C# Express and on the Menu Bar, go to Help> Register Product.




Step 2:
You will be presented with a window asking for a Registration Key. Click "Obtain a registration key online" to begin the process of obtaining the key. An internet connection is required for the following process.










Step3:
You will be taken to a page where you will be asked to log in your Windows Live ID. If you already have a Windows Live ID account, then you can sign in. If you currently don't have an account, you need to sign up for a new one by clicking the "Sign up now" button.





After signing in, you will be presented with a form that asks for certain details such as your name, email, country, and occupation. You will also answer some surveys regarding your interest on certain fields of .NET programming and how you intend to use Visual C# Express. Click "Continue" after completing the required fields. You may be required to verify your email so check your inbox for the verification email. You will see a link that you need to click in order to verify the email. After email verification, click the "Continue" button again. Wait for your registration key to pop up in your browser.

 
 
 
Copy the registration key and go back to Visual C# Express. Paste the key to the text box in the Registration Window and then click "Register Now". That's it, you can now use Visual C# Express permanently.

Welcome to Visual C# Express 2010

It is essential to know the different parts of the Visual C# Express environment. You also need to know the different tools and features that this IDE can offer to you.


Open Visual C# Express 2010, if this is your first time running the IDE, you need to wait for it to configure the initial settings for the user.




After the initial configuration, the Start Page of Visual C# Express 2010 will show up.

The numbered labels will be used to identify the different parts of the IDE.
 

The Menu Bar

The (1)Menu Bar is where the different menus for creating, developing, maintaining, debugging, and executing programs can be found.  Clicking a menu will reveal another set of related menus. Note that the menu bar still has hidden menu items which will only show on certain conditions. For example, the Project menu item will show if a project is currently active. Here are some of the description of each menu item. The following are some of the menus and their description.
Menu ItemDescription
FileContains commands to create new projects or files, open or save projects, exit or close projects, printing, and many file or project related tasks.
EditContains commands to that are related to editing such as selecting, copying, pasting, finding, and replacing.
ViewAllows you to open more windows that are initially hidden or add more toolbars items to the toolbar.
ProjectContains commands related to the projects you are working on.
DebugAllows you to compile, debug(testing), and run the project.
DataContains command for connecting or creating different datasources for use in your application.
FormatContains commands for arranging the layout of GUI components while in the Design View.
ToolsContains the different tools, settings, and options for VS/VCE.
WindowAllows you to adjust the view or layout of the windows inside VS/VCE.
HelpAllows you to view the documentation and help topics, product registration details, and product version details.

The Toolbars

The (2)Toolbars contain commonly used commands which are also found in the menu bar. The toolbars serve as a shortcut to commands located in the menu bar. Each buttons has an icon that represents their functionality. You can hover each button to show a tool tip that describes their functionality. Some commands are initially hidden and will only show up on appropriate situations. You can also right click to any blank area of the toolbar to add more commands. Alternatively, you can go to View > Toolbars and check items to show up more toolbars. Some buttons have arrows beside them that when clicked, shows more related commands. You can also click the arrows beside each toolbar that will allow you to add or remove more buttons to tool bar. The left side of each toolbar allows you to move or change the arrangement of toolbars.

The Start Page

You will see some tips, tutorials and news in the (3)Start Page section of the IDE. You can also create or open projects from here. If you have created some projects, then they will show up here in the Recent Projects section so you won't have a hard time finding each project. You can access the latest news related to .NET and Visual Studio by going to the Latest News tab. You can open VS/VCE's internal browser by going to View> Other Windows > Web Browser.

Wednesday 3 October 2012

Visual C# Express and Visual Studio


Visual Studio 2010 and Visual C# Express 2010 are Integrated Development Environments (IDE) which contain tools that aids you in developing C# and .NET applications. You can create a C# application just by using a notepad or any text editor to type your codes. You can then use the C# compiler available when you install .NET. But that can be a tedious process and errors would be hard to detect. Note that I may use the term Visual Studio to refer to both Visual Studio and Visual C# Express products.

 
 

It is recommended to use an IDE when creating programs. These IDE's are equipped with great features that helps you while developing C# applications. A lot of process that takes time to do can be automated by Visual Studio. One of the features is Intellisense which is guides you as you type your code. Another feature is the adding of break points to your code which allows you to pause the execution of code at a certain part and check the current values of the variables in your program when it is running. Visual Studio can also detect errors in your program as you type and even try to fix minor errors such as capitalization. It includes designer tools for creating graphical user interfaces which generates the long code you may type without using Visual Studio. With these powerful programs, your productivity will increase and development times will decrease thanks to their amazing features.

Visual C# Express

Visual C# Express (VCE) is free version of the Visual Studio family. It is free to download and use and it offers enough features to get you started programming C# and Windows applications. But because its free, you will be missing some great features that the other IDE, Visual Studio, offers. Nevertheless, using Visual C# Express is enough to follow most of the tutorials.
 

Visual Studio

Visual Studio (VS) is a more complete IDE packed with lots of features and tools such as creating diagrams and advanced debugging which are missing in the Visual C# Express Edition. The downside is that it will cost dollars to have a copy of this. Visual Studio is not just used for C#, but for other languages as well such as Visual Basic. It's an all-in-one tool for a Microsoft developer.
The user interface of Visual C# Express and Visual Studio is almost similar, except if you choose a different development setting for Visual Studio. I will use Visual C# Express Edition in most of its tutorials.

Downloading Visual C# Express 2010

 
The Visual C# Express 2010 is available as a free download.
Download Visual C# Express 2010
Click the Visual C# Express link instead. You will be taken to another page where download will automatically start. Chose the location where you want to save the installer. You are now ready to install Visual C# Express 2010.

What is .NET Framework

The .NET Framework ("dot net") is a platform created by Microsoft used to develop different kinds of applications targeted mainly to the Windows operating system. The .NET Framework can also be used for developing web applications. Several versions of the .NET have been released in the past and each iteration adds considerable amount of features to the earlier version. Although .NET applications are designed for Windows, some third-party companies try to port the .NET to other systems. The .NET Framework contains the  .NET Framework Class Library (FCL) which is a gigantic library of classes, structs, enumerations, basic types, and many more which are categorized into different modules or assemblies.
Common Language Runtime (CLR) is the core of .NET which runs .NET applications. It enables the .NET framework to understand a number of supported languages such as C#, Visual Basic, and C++. The code that runs under the CLR and .NET is called managed code because the CLR manages different aspects of your application during runtime.
During compilation, source codes are compiled into Common Intermediate Language (CIL) which is closely identical to assembly language. We have to convert our source code into CIL because it is the only language that can be understood by .NET. For example, codes in C# and Visual Basic both compile to CIL. That is why different .NET applications written in different languages can still communicate to each other. If you want a language to be .NET-compatible, you can create a compiler that compiles your code into the Intermediate Language. The compiled CIL is stored in an assembly such as a .exe or .dll file.
Once your code is compiled to Common Intermediate Language, the job is transfered to the Just-In-Time (JIT) compiler. The JIT compiles the CIL code into native code(the language of computers) only when that part of code is needed by the program (hence the term "just in time"). The compiled native code is automatically optimized for the current OS or machine. This is one advantage of using .NET.
The following summarizes how your C# code is transformed into a machine executable program.
  1. The programmer writes a program in a .NET compatible language such as C#.
  2. The C# code is compiled into its CIL equivalent code.
  3. The CIL is stored in an assembly.
  4. When the code is executed, the JIT compiles the CIL code to native code that the computer can execute.
The .NET Framework also has a feature called the Common Type System (CTS). This is the mapping of the data types specific to a language to its equivalent type in the .NET Framework. Data types are representations of data. For example, whole numbers are represented by the integer data type. With CTS, the int data type in C# and the Integer data type in Visual Basic are the same because both are mapped to the .NET type System.Int32.
Garbage collection is another feature of the .NET Framework. When resources are no longer in use, .NET Framework frees up the memory used by an application. The garbage collector is called whenever it is needed by an application although you can call GC manually to clean up resources for you.
To be able to run a .NET application, you must first install it in your computer. Latest release of Windows 7 operating system has .NET pre-installed. If your system doesn't have .NET installed yet, you can download it by clicking the link below:
Microsoft .NET 4.0 Download
After downloading, run the installer and follow the instructions. You might need to restart the computer after/during installation.
(.NET 4 will also be installed if you install Visual C# Express or Visual Studio 2010 as we will see later).

Saturday 29 September 2012

Common Type System (C# Programming Language)


C# has a unified type system. This unified type system is called Common Type System (CTS).

A unified type system implies that all types, including primitives such as integers, are sub-classes of the System.Object class. For example, every type inherits a  ToString() method.


Categories of data types


CTS separates data types into two categories:
• Value types
• Reference types

Instances of value types do not have referential identity nor referential comparison semantics - equality and inequality comparisons for value types compare the actual data values within the instances, unless the corresponding operators are overloaded. Value types are derived from System.ValueType, always have a default value, and can always be created and copied. Some other limitations on value types are that they cannot derive from each other (but can implement interfaces) and cannot have an explicit default (parameterless) constructor. Examples of value types are all primitive types, such as int (a signed 32-bit integer), float (a 32-bit IEEE floating-point number), char (a 16-bit Unicode code unit), and System.DateTime (identifies a specific point in time with nanosecond precision). Other examples are enum (enumerations) and struct (user defined structures).

In contrast, reference types have the notion of referential identity - each instance of a reference type is inherently distinct from every other instance, even if the data within both instances is the same. This is reflected in default equality and inequality comparisons for reference types, which test for referential rather than structural equality, unless the corresponding operators are overloaded (such as the case for System.String). In general, it is not always possible to create an instance of a reference type, nor to copy an existing instance, or perform a value comparison on two existing instances, though specific reference types can provide such services by exposing a public constructor or implementing a corresponding interface (such as ICloneable or IComparable). Examples of reference types are object (the ultimate base class for all other C# classes), System.String (a string of Unicode characters), and System.Array (a base class for all C# arrays).
Both type categories are extensible with user-defined types.


Boxing and Unboxing



Boxing is the operation of converting a value-type object into a value of a corresponding reference type. Boxing in C# is implicit.

Unboxing is the operation of converting a value of a reference type (previously boxed) into a value of a value type. Unboxing in C# requires an explicit type cast. A boxed object of type T can only be unboxed to a T (or a nullable T).

For Example :

int foo = 42;// Value type.
object bar = foo;     // foo is boxed to bar.
int foo2 = (int)bar;  // Unboxed back to value type.

Generics

Generics were added to version 2.0 of the C# language. Generics use type parameters, which make it possible to design classes and methods that do not specify the type used until the class or method is instantiated. The main advantage is that one can use generic type parameters to create classes and methods that can be used without incurring the cost of runtime casts or boxing operations.

For Example:

// Declare the generic class.
 
public class GenericList<T>
{
    void Add(T input) { }
}
 
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList<int> list1 = new GenericList<int>();
 
        // Declare a list of type string.
        GenericList<string> list2 = new GenericList<string>();
 
        // Declare a list of type ExampleClass.
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}

Friday 28 September 2012

Distinguishing features of C# Programming Language


C# is the programming language that most directly reflects the underlying Common Language Infrastructure (CLI).Most of its intrinsic types correspond to value-types implemented by the CLI framework. However, the language specification does not state the code generation requirements of the compiler: that is, it does not state that a C# compiler must target a Common Language Runtime, or generate Common Intermediate Language (CIL), or generate any other specific format. Theoretically, a C# compiler could generate machine code like traditional compilers of C++ or Fortran.

Some notable features of C# that distinguish it from C and C++ (and Java, where noted) are:

  • It has no global variables or functions. All methods and members must be declared within classes. Static members of public classes can substitute for global variables and functions.
  • Local variables cannot shadow variables of the enclosing block, unlike C and C++.
  • C# supports a strict Boolean data type, bool. Statements that take conditions, such as while and if, require an expression of a type that implements the true operator, such as the boolean type. While C++ also has a boolean type, it can be freely converted to and from integers, and expressions such as if(a) require only that a is convertible to bool, allowing a to be an int, or a pointer. C# disallows this "integer meaning true or false" approach, on the grounds that forcing programmers to use expressions that return exactly bool can prevent certain types of common programming mistakes in C or C++ such as if (a = b) (use of assignment = instead of equality ==).
  • In C#, memory address pointers can only be used within blocks specifically marked as unsafe, and programs with unsafe code need appropriate permissions to run. Most object access is done through safe object references, which always either point to a "live" object or have the well-defined null value; it is impossible to obtain a reference to a "dead" object (one that has been garbage collected), or to a random block of memory. An unsafe pointer can point to an instance of a value-type, array, string, or a block of memory allocated on a stack. Code that is not marked as unsafe can still store and manipulate pointers through the System.IntPtr type, but it cannot dereference them.
  • Managed memory cannot be explicitly freed; instead, it is automatically garbage collected. Garbage collection addresses the problem of memory leaks by freeing the programmer of responsibility for releasing memory that is no longer needed.
  • In addition to the try...catch construct to handle exceptions, C# has a try...finally construct to guarantee execution of the code in the finally block, whether an exception occurs or not.
  • Multiple inheritance is not supported, although a class can implement any number of interfaces. This was a design decision by the language's lead architect to avoid complication and simplify architectural requirements throughout CLI.
  • C#, like C++, but unlike Java, supports operator overloading.
  • C# is more type safe than C++. The only implicit conversions by default are those that are considered safe, such as widening of integers. This is enforced at compile-time, during JIT, and, in some cases, at runtime. No implicit conversions occur between booleans and integers, nor between enumeration members and integers (except for literal 0, which can be implicitly converted to any enumerated type). Any user-defined conversion must be explicitly marked as explicit or implicit, unlike C++ copy constructors and conversion operators, which are both implicit by default. Starting with version 4.0, C# supports a "dynamic" data type that enforces type checking at runtime only.
  • Enumeration members are placed in their own scope.
  • C# provides properties as syntactic sugar for a common pattern in which a pair of methods, accessor (getter) and mutator (setter) encapsulate operations on a single attribute of a class. No redundant method signatures for the getter/setter implementations need be written, and the property may be accessed using attribute syntax rather than more verbose method calls.
  • Checked exceptions are not present in C# (in contrast to Java). This has been a conscious decision based on the issues of scalability and versionability.
  • Though primarily an imperative language, since C# 3.0 it supports functional programming techniques through first-class function objects and lambda expressions.