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:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home