Xceedas

Xceedas
xceedas

Saturday, 13 September 2014

Tutorial C# Core : Variables

Introducing Variables
I asked a six a year old, what are variables? She replied, I don't know… I guess… someone who is very able? See, they have an answer for everything! I am like, OK, fair enough. Now, if you happened to stumble upon here to learn what the heck variables in C# are then my friend you are in luck, today I am just going to do that. Before I start, should I ask you the same question, be creative don't copy that little genius, you can put your answer in the comments below. 

This article is for the beginners of C#. If you are not, you are still welcome to continue to read. Maybe you can comment on my conversational style of writing or bring in your experience of techno jargon questions to little ones. Ok, back to the topic now, here is my take on a core feature of C# programming language, introducing variables!

So, what is a variable? If you ask me what is my first name? I will say, Asif. See, now my first name is stuck in you brain, God knows where, but, whereever it is in your brain's memory that place is variable storage that has the information Asif in it. Now I am not going into the details of how much time you will retain this information in your brain and so on, no way I can go to medical school and even make an attempt to find that out. Wait a minute, computers have a brain? No. They have memory, that is like storage of information. The point is, computer uses memory place holders using variables to remember information, or in the computing world often referred to as Data.

Variables sit in the computer's memory, we get it, now how does that happen? What magic does C# do for it to happen? Trust me, it's easy, I mean really easy. Let us begin by letting the computer know what we want to store in memory. Computer, I want you to remember my lucky number 9 (mine is 7 by the way). No mater how hard I will scream in front of the computer, nothing will happen! (please I am in no mood to talk about speech recognition now). We will not do that, rather we will ask the C# language to do the talking. Let's see how to ask C# to tell the computer to take note of our variable and the information we want to store with it.

Declaration, Assignment and Initialization
Using variables, the computer maintains our information, in C# we can code the variable declaration with the following syntax:
  1. datatype identifier;  
The preceding line is called a C# statement, typically C# statements end with a semi-colon. The word “datatype” lets the computer know what kind of data we want to store, is it text (like first name) or a number (like age) and so on. The word “identifier” lets the computer know how we want to name the place holder were the first name or age is stored. Can I see the real C# example please? Sure, here you go:
  1. int age;  
The preceding statement declares a variable named age with a data type of int (integer). After the declaration, now we can tell the computer to store the value in our newly declared variable, using something called an assignment operator “=”. This is how it looks like:

age = 25; (You might argue, I'm 25.5 years old, sure, we can store that too but not with the int data type.)

You can also declare and assign or initialize at the same : int age = 33; 

Yes, you can also declare and assign multiple variables in the same statement, just note that all of them should be of the same data type:
  1. int age = 20, luckynumber = 9;  
To declare variables of different types, you need to use separate statements. We cannot assign different data types in single statement:
  1. int age = 20;  
  2. bool iamgenious = true// Creates a variable that stores true or false  
  3. int x = 10, bool iamgenious = true// This statement will produce compile time errors  
Compilation is a process by which the computer understands our English-like statements by its own processing mechanism. So, what is “bool”? Well, it is just like int, that is another kind of data type. Is bool the same as int? No, they are not. An int stores numbers and bool stores either Yes/No or True/False (no, Maybe is not allowed). Don't worry, C# has a rich set of various data types to handle all sorts of data. You will also notice the "//"; this is a special C# instruction to the compiler to basically ignore anything that follows the “//”. It is called comments, mostly used by coders to provide notes/remarks to emphasize the importance or anything else they feel about that specific statement. Mostly done in good faith by cool coders to help themself or someone else to understand what the heck this statement is doing! It is a safe and good practice to always initialize variables, well before we start using it in some part of any given process. If we fail to do so, the C# compiler will not like it and be mad at us, you know giving errors. This prevents us from unintentionally retrieving potential bad data values from the memory. So, if you don't want to see the error: Use of unassigned local variable 'age' than always remember to initialize your variables.

The "var" Keyword
Remember when we declare int age = 10; we basically told the compiler explicitly the variable is of integer type. Now, if we do the same declaration like : var age = 10; then we are letting the compiler determine the data type at run-time implicitly. In this case it is an integer, because it stores the data “10” which is a number with no digits. Not to be surprised here, the compiler basically treats both statements as the same. If you want to use the "var" keyword for declaration, the “Scope” of the variable becomes important, it is mostly local. We will see the scope soon. On an advanced side note, we cannot use the keyword "var" to declare field/property/parameter/return types (I hope to cover them soon in future articles).

Scope
Scope, commonly also referred to as visibility, is very important when we declare a variable. It is good to determine the visibility aspect before we declare a variable. Suppose we are coding a complex process and a specific variable is used in many different parts of it, then it makes sense to declare it as Public visibility. In the case of a variable that is only needed to be used during the life of any looping or any specific code block that starts and ends with curly braces {}, we can stick to Private visibility. Once we declare a variable public, we cannot declare the same variable name with private visibility. Take a look a the following scope example using a loop: 
  1. for (int count = 0; count < 10; count++)  
  2. {  
  3.     Console.WriteLine(count);  
  4. // variable “count” goes out of scope here  
For the sake of simplicity of this beginner tutorial I am not covering the other available scopes: Protected, Friend and ProtectedFriend in this specific article. Once again, scoping helps us in the use of the variable within a code block, inside a method/function, class level or at the global project level.

Constant Variables
As the name suggests, we define a constant variable with a purpose to retain its value throughout its life cycle. Check out the following statement, all we need to do is add the keyword const in front of the data type and assign it a value:

const int maximum_runs = 100; // This value cannot be changed.

Do we store constants in our brain? I guess many of us do, only preferences change from one to another. What is your favorite constant anyway? I told you mine already, the lucky number 7. Do share some of yours, I hear one: super_hero = “Spider Man”, is it? Constants generally make the code easier to read and modify. For example, if you define a constant called Max_Age_Limit and initialize it to 60, now down the road if you want to change this to reflect 65 instead, all you need to do is change it in one place and it affects all the places where Max_Age_Limit is used for any purpose.

As we progress toward more advanced aspects of C#, we will need to deal with some other forms of variables such as: value types of variables, like enum and reference types of variables like class and static variables, that I will hope to cover in some future article.

C# includes support for the following built-in data types:

Data TypeRange
byte0 .. 255
sbyte-128 .. 127
short-32,768 .. 32,767
ushort0 .. 65,535
int-2,147,483,648 .. 2,147,483,647
uint0 .. 4,294,967,295
long-9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807
ulong0 .. 18,446,744,073,709,551,615
float-3.402823e38 .. 3.402823e38
double-1.79769313486232e308 .. 1.79769313486232e308
decimal-79228162514264337593543950335 .. 79228162514264337593543950335
charA Unicode character.
stringA string of Unicode characters.
boolTrue or False.
objectAn object.
Here is an example of variables in action using a console application:
  1. namespace VariablesDemo  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             short x = 10;  
  8.             int y = 50;  
  9.             double z;  
  10.             z = x + y;  
  11.             Console.WriteLine("x = {0}, y = {1}, z = {2}", x, y, z);  
  12.             Console.ReadLine();  
  13.         }  
  14.     }  
  15. }  
Assuming your demo code compiles and runs, you will see the following output on the console screen: x = 10, y = 50, z = 60

No comments :