Saturday, March 28, 2009

sss

Friday, February 20, 2009

Variables and Types

All "normal" applications requires a storage space for data, whether you want to store a number, a string (sequences of characters) or some other data.

You can think of variables as a container for data, there are many types of containers, each of them can store a specific type of thing. For instance you have a box that can store just yellow items, you cannot throw in a item with another colour it will get rejected (might not be true but just let it be for now).

Lets go through variables with some hands-on experience.

Do ignore the rest of the codes and just concentrate on the highlighted part, all the codes you enter will only change in between the two braces surrounding the highlighted part as shown.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{

}
}
}
Every variable has a name (known as the identifier) and a specific type they can hold, you declare a variable in C# using this syntax.
type variable_name;
There are some restrictions on the naming the identifiers:
  • The identifier must start either with a letter or a underscore character (_)
  • C# keywords cannot be used as variable names
As well as some details to be noted
  • C# is a case-sensitive language (bird and Bird are two different identifiers)
  • C# identifier can contain digits, letters and underscore and unicode characters (you should not name your variables with them anyway its not advised...)
  • You should name your variables according to the data that you are storing (eg. name)
Hence here are some of the valid and invalid variable names
_myIntegerValid
MyStringValid
55CoconutsInvalid (should not start with a digit)
foreachInvalid (should not be a C# keyword)
My-ItemInvalid (illegal character not allowed)

So now that we have the restrictions set lets try out some programming with variables

Labels:

Simple Overview

Today i will start on the basic syntax of C#.. first we will see a typical hello world application in C# and i'll try explaining them step by step.

First you have to create a new console application.. The reason why we start with console applications is mainly because you get to familiarise with the syntax (rules and principles of a language that you must follow) before you continue to windows applications.. i know its boring but please bear with it!.

First you open Visual C# Express 2008, or Visual Studio 2008.
The difference between the two IDE is mainly the language supported, Visual Studio supports more languages.. and since its a commercial IDE (VCE is free) there are more functionality than the Express versions.. some of which include class diagram, conditional breakpoints etc.

As i am using Visual Studio 2008, there might be some difference but i am sure its almost the same.
  1. Click on File Menu > New > Project.
  2. Make sure you are using Visual C# as the language, Under Visual C# > Windows choose Console Application then give it a name, in my case i named it HelloToMe and press OK. The IDE will generate the required files
  3. Double click the Program.cs file on the Solution Explorer (by default it should be on the top right corner) and enter the highlighted line as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloToMe
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello To ME!"); //outputs Hello To ME!
}
}
}
After which you can click on the Green button which says Start Debugging which will result on the following output on the console window.
Hello To ME!

Congrats~ Now you have made your first application (hopefully and maybe not =s). Either way we still have to go through the codes. Don't worry if you don't understand the terms used. Slowly you will...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
The first four lines of codes as seen here is the are called using directives, it is used by the compiler to look for types in used in your classes if you do not provide a fully qualified name for your types used, they are used to save time typing the full name.

using System; //with using System;
Console.WriteLine("Hello");
Console.WriteLine("Hello Again");
Console.WriteLine("Hello Again and Again!");

System.Console.WriteLine("Hello"); //without using System; (fully qualified name)
System.Console.WriteLine("Hello Again");
System.Console.WriteLine("Hello Again and Again!");
Example: Without using directives vs With using directives

Next, we have the namespace declaration in line 6 (This is the namespace that is related to the previous using directives).
Namespaces are used to organise and group types together under a name to avoid crashes among different types with the same name.

It is recommended that name your namespace according to your company name followed by your department name and sub-department so on.. for example (Rejinderi.HumanResources.CoffeeMakers). The levels of the namespace can be specified using the . dot operator.The dot operator has a couple of other usage most importantly as member access operator but we won't talk about those now.

Namespaces can be nested so the following two namespaces are actually the same they can be referred by Rejinderi.HumanResources
namespace Rejinderi.HumanResources
{
class MyClass //fully qualified name: Rejinderi.HumanResources.MyClass
{
}
}

namespace Rejinderi
{
namespace HumanResources
{
class MyClass //fully qualified name: Rejinderi.HumanResources.MyClass
{
}
}
}
Classes and types will be covered later on.
Next we have the Main method

static void Main(string[] args)
{
Console.WriteLine("Hello To ME!"); //outputs Hello To ME!
}
Method is a code block (surrounded by parenthesis {}, so are types and namespaces) that performs a routine.
They may or may not return a value according to the return type in this case the keyword void specifies that the method has no return type.
They can receive information called parameters through a parameter list.

In this case string[] args is the one and only parameter for this method.
Methods will be covered in detail later on, the Main method (as shown above) is a special method as it is the first execution point for all C# applications. It is automatically called when the application executes. You execute a method by calling them.

Lastly for this application we have the Console.WriteLine method call, which you added in yourself, what this method does is prints a line to the console application screen followed by a carriage return (new line), it accepts a variety of overloads(parameter list types, 19 to be exact).
You call a method by specifying the method name (Console.WriteLine) followed by open bracket then the parameter(s) to pass in then the close bracket. Followed by a semi colon.
In this case it would be
  • Method Name: Console.WriteLine
  • Parameter: "Hello To ME!"
Take note that all C# statements end with a semi colon.
Again, please do not worry about the things you don't understand here, they will be covered soon.

Labels:

Thursday, February 19, 2009

Introduction

Okay.. i have decided to make this a tutorial-like blog (for now..) so if you want to learn from the very basics this is just the place to start!

Do comment on mistake you see, i try to provide the best information according to my knowledge... Thanks.

Basic requirements you'll need
  • A Integrated Development Environment (IDE)
    I would recommend using Visual Studio or Visual C# Express
    If you don't have one you can download the Visual C# Express IDE for free
  • .NET Framework installed
Basic Information

So what exactly is C#?
C# is a simple, modern, object-oriented and type-safe programming language created by Microsoft for the .NET Framework platform.

So what is the .NET Framework?
According to Wikipedia, The Microsoft .NET Framework is a software technology that is available with several Microsoft Windows operating systems

If you do not care about the .NET Framework or find the next section confusing and just want to continue to the coding parts you can skip this post now (hopefully come back later on).
Do read on if you want to know more about the .NET framework or find references on the web. Remember that if you wish to be a better/successful .NET programmer it is important to know about the .NET Framework!

More about .NET Framework

.NET Framework is a set of tools and services. The main items of .NET Framework consists of the following: Common Language Specification (CLS), Common Type System (CTS), Framework Class Library (FCL) and Common Language Runtime (CLR)

Diagram: .NET Framework architecture (taken from codeguru.com)

As you can see from the diagram, C# is not the only language that supports the .NET Framework, but C# is the first language to be created specifically for the .NET Framework! and that is something to be proud of =).

Now i am going to explain briefly on the important components of the .NET Framework if you need a complete specification i suggest you to look up on MSDN.

Common Language Specification (CLS)
Common Language Specifications is a set of base rules that any language targeting the Common Language Infrastructure/.NET must follow. It works with the CTS to ensure language interoperability.

The Common Language Infrastructure is a set of standards defined so that applications written in multiple high-level languages that targets it can be executed in different system environment (different platform: Windows, Linux) without the need to rewrite the application.

Common Type System (CTS)
CTS is a standard that describe a set of type for basic primitive datatypes (eg. String, Integer, Floating Types) in which languages that target the .NET Framework should map (eg.int in C# and Integer in VB.NET both maps to Int32 in the CTS) to for interoperability (interact/share information/communicate) with other languages.

Thus, with aid of CTS, interoperability standards are way better than before, it means that you can actually see the transfer of execution when for example a C# application calls a VB.NET library function which makes debugging applications made in more than one language way simpler.

Framework Class Library (FCL)
The Framework Class Library is a set of libraries with common and useful methods you can use. As you will see later on is one of the biggest advantage you get being a .NET developer, it includes a very very wide range of libraries that you will most likely be using.

Common Language Runtime (CLR)
Finally! Common Language Runtime the last and most important core feature of the .NET Framework. The CLR is the .NET Framework's runtime execution environment. Application codes that run under the management of the CLR are termed as managed code.

Diagram: Managed vs Unmanaged code
Normal applications that compile directly to machine specific code are called unmanaged code whereas applications that compile through the .NET compiler are called managed code (IL code).
From the above diagram, the blackbox surrounding the JIT Compiler and x86 Machine Code is part where the CLR manages the execution of the application.

Therefore, there is two steps of compilation for .NET applications
  1. Source code to IL code
  2. IL code to platform specific code
By using this method there are several advantages.
  1. You get platform independence, the IL code can be placed on another platform before they are compiled to machine specific code by the runtime. Although there is no Microsoft implementation at this time of writing. The Mono Project enables .NET programmers to have their codes portable to platforms such as Linux and Mac.
  2. Under the management of CLR, you get a performance improvement as machine codes are generated in a method-by-method basis during which means that functionaility that you do not need to use during runtime will not be compiled to machine code, you save time and space on the compilation process
  3. With the JIT compilation on the target machine (the machine that runs the application) the CLR knows exactly what platform it is running on, this way it can perform code optimization for that specific platform.
The CLR itself contains the following services
  • Garbage collector(GC) - Automatically remove data in the memory that are no longer needed.
  • Exception handling - Handles errors or conditions that changes the normal way of execution in a clean manner.
  • Security - Provides many security features such as role management.
  • Thread management - Manages thread execution

More about C#

The C# project is started during December 1998 (More than 10 years ago) with the goal of creating a programming language that is simple, modern, object-oriented and type-safe for the .NET platform (Not named at that time).

Currently, C# (Currently at version 3.0, 4.0 is releasing soon...) has grow so much with over a million programmers programming with it.

C# compiles to IL code (managed application) and runs under the control of CLR.
So some of you might be thinking "Will this affect the performance?". Unfortunately its a yes, managed applications runs slower than unmanaged applications because of all the type-checking and management but the amount of speed difference is very very little you should not worry about unless you need to program a mission critical application. If so, you should program with languages like C++ instead.

So why would you want to use .NET/C#?
I would say that you get far more benefits which will outweigh the performance loss. With features such as the Garbage Collection you would not have to worry about memory management yourself (unless you use resources that do not belong to you) and the type-checking feature of the CTS you get less prone to bugs/errors in your application. And most importantly you get to use a set of ready made libraries developed with the best design available!

I will end here for now, if there should be anything anyone wish to add or change do post a comment. I do not have the time and ability to cover everything.. Sorry!

Labels: