Click here to Skip to main content
15,886,795 members
Articles / Programming Languages / C#

Tutorial–C# Core : Variables

Rate me:
Please Sign up or sign in to vote.
3.38/5 (10 votes)
10 Sep 2014CPOL8 min read 22K   9   19
My attempt to get beginners some insight into C#, through this series of short articles

Introducing Variables

Me to a six a years old, what is Variables? She replies, I don’t know… I guess… someone who is very able? See, they got answer for everything! I am like, OK, fair enough. Now, if you happen to stumble upon here to learn what the heck Variables in C# are? You my friend 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 comments below.

This post is for the beginners of C#. If you are not, you are still welcome to continue to read. May be 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 the VARIABLES!!!

So, what is 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, where ever it is in your brain memory that place is variable storage which has information Asif in it. Now I am not going to into the details of how much time you will retain this information in your brain etc., no way I can go to medical school and even make an attempt to find that out. Wait a mint, computers have brain? No. They have memory, which is like storage of information. The point is, computer uses memory place holders with help of variables to remember information, or in computing world often refer as Data.

Variables sit in the computer memory, we get it, now how it happens? What magic does C# does for it to happen? Trust me its easy, I mean really easy. Let us begin with letting computer know what we want to store in the 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 no mood to talk speech recognition now). We will not do that, rather we will ask the C# language to do the talking. Let’s see how we can 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

With the help of variables, computer keep track of our information, in C# we can code the variable declaration with the following syntax:

datatype identifier;

The above mention line is called a C# statement, typically c# statements ends with a semi-colon. The word “datatype” lets computer know what kind of data we want to store, is it text (like first name) or number (like age) and so on. The word “identifier” lets 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:

int age;

The above statement declares an variable named age with a data type of int (integer). After the declaration, now we can tell computer to store the value in our newly declared variable, using something called 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 variable in the same statement, just keep in might all of them should be of same data type:

int age = 20, luckynumber = 9;

To declare variables of different types, you need to use separate statements. We cannot assign different data types on a same single statement:

int age = 20;
bool iamgenious = true; // Creates a variable that stores true or false
int x = 10, bool iamgenious = true; // This statement will produce compile time errors

Compilation is a process by which computer understands our English like statements to its own processing mechanism. So, what is “bool”? Well, it is just like int, that is another kind of data type. Is bool same as int? No, they are not. Int stores numbers and bool stores either Yes/No or True/False ( no Maybe not allowed). Don’t worry C# has rich set of different data types to handle all sorts of data. You will also notice the // this is special C# instruction to compiler to basically ignore anything that follows the “//”. It is called comments, mostly used by coders to use as notes/remarks to emphasize the importance or anything else they feel about that particular statement. Mostly done in good faith by cool coders to help self or someone else to help out 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, 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; we are letting compiler figure out the data type at run-time implicitly it is integer, because it stores the data “10” which is a number with no digits. Not to be surprised here, compiler basically treats both statement as same. If you want to use the ‘var’ keyword for declaration, the “Scope” of variable is become important, it is mostly local. We are going to see the scope soon. On a advance side note, we cannot use the keyword 'var' to declare field/property/parameter/return types (hope to cover them soon on next coming posts).

Scope

Scope, commonly also refer as visibility, is very important when we declare any variable. It is good to determine the visibility aspect before we declare any variable. Suppose, we are coding a complex process and a particular variable is used in many different parts of it, then it makes sense to declare it as Public visibility. In case if of a variable which is only need to be used during life of any looping or any particular code block with start 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:

for (int count = 0; count < 10; count++)
{
     Console.WriteLine(count);
}  // variable "count" goes out of scope here

For sake of simplicity of this beginner tutorial I am not covering the other available scopes: Protected, Friend and ProtectedFriend in this particular post. Once again, scoping helps us in 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 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 a lot of us do, only preferences changes from one to another. What is your favorite constant anyway? I told you mind already lucky number 7. Do share some of yours, I hear one: super_hero = “Spider Man”, is it? :) Constants generally makes code easier to read and modify. For example, if you define a constant call 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 of any purpose.

As we progress toward more advance aspects of C#, we will have to deal with some other forms of variables such as: value types of variable like enum and reference types of variables like class, and static variables, which I will hope to cover in some future post.

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

Data Type Range
byte 0 .. 255
sbyte -128 .. 127
short -32,768 .. 32,767
ushort 0 .. 65,535
int -2,147,483,648 .. 2,147,483,647
uint 0 .. 4,294,967,295
long -9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807
ulong 0 .. 18,446,744,073,709,551,615
float -3.402823e38 .. 3.402823e38
double -1.79769313486232e308 .. 1.79769313486232e308
decimal -79228162514264337593543950335 .. 79228162514264337593543950335
char A Unicode character.
string A string of Unicode characters.
bool True or False.
object An object.

Here is an example of variables in action using console application:

namespace VariablesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            short x = 10;
            int y  = 50;
            double z;

            z = x + y;
            Console.WriteLine("x = {0}, y = {1}, z = {2}", x, y, z);
            Console.ReadLine();
        }
    }
}

Assuming your demo code compiles and runs, you will see the following output on console screen: x = 10, y = 50, z = 60

In my next installment in this series I will write about different usage scenarios of data types and some more related goodies… I’m always looking forward to any constructive criticism, and who doesn’t like little praise eh! I hope the content provided you with some good insight about one of the core feature of C# and you also enjoyed it.

This article was originally posted at http://dotnetsme.com/post/tutorial-c-core-variables

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect FeatherSoft Inc.
Canada Canada
Asif Sayed has over twenty + years experience in software development and business process architecture. He has a consulting firm in Toronto, Canada. His firm provides IT solutions to all sizes of industries. He also teaches .NET technologies at Centennial College in Scarborough, Ontario. Recently he has become member of team as a subject matter experts with Microsoft's Learning Division. He has a book published by Apress with the Title "Client-Side Reporting with Visual Studio in C#".

My blog: http://www.dotnetsme.com
My Website: http://www.feathersoft.ca

Comments and Discussions

 
AnswerLet me guide you... Pin
Afzaal Ahmad Zeeshan22-Mar-15 2:22
professionalAfzaal Ahmad Zeeshan22-Mar-15 2:22 
GeneralMy Vote 5 Pin
Shemeemsha (ഷെമീംഷ)24-Sep-14 0:06
Shemeemsha (ഷെമീംഷ)24-Sep-14 0:06 
QuestionComments, vote of 3 Pin
KP Lee14-Sep-14 13:22
KP Lee14-Sep-14 13:22 
AnswerRe: Comments, vote of 3 Pin
Asif Sayed14-Sep-14 13:27
Asif Sayed14-Sep-14 13:27 
GeneralRe: Comments, vote of 3 Pin
KP Lee14-Sep-14 13:39
KP Lee14-Sep-14 13:39 
QuestionVoted 3 Pin
KP Lee14-Sep-14 12:44
KP Lee14-Sep-14 12:44 
AnswerRe: Voted 3 Pin
Asif Sayed14-Sep-14 13:19
Asif Sayed14-Sep-14 13:19 
NewsRe: Voted 3 Pin
KP Lee14-Sep-14 13:37
KP Lee14-Sep-14 13:37 
QuestionTypes Of Variables Pin
milo-xml12-Sep-14 7:49
professionalmilo-xml12-Sep-14 7:49 
AnswerRe: Types Of Variables Pin
Asif Sayed12-Sep-14 9:30
Asif Sayed12-Sep-14 9:30 
GeneralMy vote of 5 Pin
viler8412-Sep-14 5:09
viler8412-Sep-14 5:09 
GeneralRe: My vote of 5 Pin
Asif Sayed12-Sep-14 6:11
Asif Sayed12-Sep-14 6:11 
QuestionConstant variables? Pin
Paulo Zemek11-Sep-14 3:53
mvaPaulo Zemek11-Sep-14 3:53 
AnswerRe: Constant variables? Pin
Asif Sayed11-Sep-14 4:04
Asif Sayed11-Sep-14 4:04 
AnswerRe: Constant variables? Pin
KP Lee14-Sep-14 12:28
KP Lee14-Sep-14 12:28 
GeneralRe: Constant variables? Pin
Paulo Zemek14-Sep-14 12:33
mvaPaulo Zemek14-Sep-14 12:33 
I am Brazilian, so English isn't my native language either.
But we can see things differently and say that I was arguing about constant vs variables exactly because in English they aren't as enforced as in Portuguese... in that case, that was my fault.
GeneralRe: Constant variables? Pin
KP Lee14-Sep-14 12:59
KP Lee14-Sep-14 12:59 
GeneralRe: Constant variables? Pin
Paulo Zemek14-Sep-14 13:05
mvaPaulo Zemek14-Sep-14 13:05 
GeneralRe: Constant variables? Pin
KP Lee14-Sep-14 13:44
KP Lee14-Sep-14 13:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.