Variables in C# – Tutorial and Examples

C# Variables Tutorial and Examples

A variable in programming domain is a program element that stores a value.

Or more technically it is a named piece of memory that can hold data of a specific type.

For instance a program can allocate 4 bytes of memory for storing an integer.

It points to a location in the memory that has data of a given type. These locations might contian:

  • Number
  • String
  • Charater
  • Date
  • Object etc

Use of Variable

The main use of variables by a program is to:

  • Hold and Manipulate values.

Variable Decalaration

Variables are decared using the following syntax:

    data_type identifier

where the data_type is the type of data while the identifier is the custom name you asign a variable.
For example say we want to create a variable to hold age of a person:

int age;

So in this case int is the data type while age is the identifier. However, we cannot use this age variable as it's not yet initialized with a value. Trying to do so causes the compiler to raise an error:

EXAMPLE

    namespace Variables
    {
        class Program
        {
            static void Main(string[] args)
            {
                int age ;
                System.Console.WriteLine(age); //cannot compile since age doesn't have a value yet
            }
        }
    }

Variable Initialization/Value Assignment

The mere declaration of a variable is not important. We need to assign the value to be stored in the memory for use by our program.
C# uses two mechanism to ensure that variables are initialized before use.

  1. Local variables(to a method) have to be explicitly initialized before use.
    Hence this below example cannot be compiled.
    EXAMPLE

    ```csharp
    namespace Variables
    {
    class Program
    {
    static void Main(string[] args)
    {
    int age ;
    System.Console.WriteLine(age); //cannot compile since age doesn't have a value yet
    System.Console.ReadKey();
    }
    }
    }

  2. Class variables(fields in a struct or class) will be defaulted to zero when not initialized explicitly.
    Hence this below example can be compiled and prints out 0

    namespace Variables
    {
    class Program
    {
    static int age;
    
         static void Main(string[] args)
         {
             System.Console.WriteLine(age); //cannot compile
             System.Console.ReadKey();
         }
     }
    }
    age = 55;

    where age is the variable identifier, = is our assignment operator while 55 is the value.

You can also just combine both declaration and assignment into one line. This makes your code more compact.

int age = 55;

EXAMPLE

    namespace Variables
    {
        class Program
        {
            static void Main(string[] args)
            {
                int age = 55;
                System.Console.WriteLine("So and so has an age of "+age);
                System.Console.ReadKey(); //this cause the console window to wait for us to type any key before exiting
            }
        }
    }

RESULT

    So and so has an age of 55

In situations where you have more than one variables and they are of the same data type. Then you can combine their declarations and assignent into a single line.

    int decade = 10, century = 100, millenium = 1000;

EXAMPLE

namespace Variables
{
class Program
{
static void Main(string\[\] args)
{
int decade = 10, century = 100, millenium = 1000;
System.Console.WriteLine("DECADE: "+decade+" CENTURY: "+century+" MILLENIUM: "+millenium);
System.Console.ReadKey(); //this cause the console window to wait for us to type any key before exiting
}
}
}

RESULT

DECADE: 10 CENTURY: 100 MILLENIUM: 1000

However if they are of different data types the you have no option but to declare them separately.

    int decade = 10;
    bool currentCentury = true;

EXAMPLE

namespace Variables
{
class Program
{
static void Main(string\[\] args)
{
int decade = 10;
bool currentCentury = true;
System.Console.WriteLine("DECADE: "+decade+" CURRENT CENTURY: "+currentCentury);
System.Console.ReadKey(); //this cause the console window to wait for us to type any key before exiting
}
}
}

RESULT

DECADE: 10 CURRENT CENTURY: True

`

Variable Initialization with Type Inference

C# is a modern programming language. It has the ability for the compiler to automatically figure out the types of variables based on the values they have been assigned. This gives C# the same ease of use and flexibility like dynamicallyed typed languages like python and ruby. Even though C# itself is a statically typed language. This ability is what we call Type Inference.
e.g

    var age = 55;

However, to use type inference, you have to assign your variable a value. This makes sense because the compiler uses that value to figure out the data type. If you don't provide one then it can't figure out.
This example here cannot compile:

namespace Variables
{
class Program
{
static void Main(string\[\] args)
{
var data; //cannot compile, you have to assign value first
System.Console.WriteLine(data);
System.Console.ReadKey(); //this cause the console window to wait for us to type any key before exiting
}
}
}

Now if we assign the value it compiles.

    namespace Variables
    {
        class Program
        {
            static void Main(string[] args)
            {
                var data = 55;
                System.Console.WriteLine(data+"is of type "+data.GetType());
                System.Console.ReadKey();
            }
        }
    }

RESULT

    55 is of type System.Int32

You can find the type of a variable programmatically using the GetType() method. This method returns the Type object and it belongs to the System.Object base class.

EXAMPLE - Get data types of variables programmatically

Let's use the GetType() method of System.Object class to get the data types of various type infered variables.

using System;
namespace Variables
{
class Program
{
static void Main(string\[\] args)
{
var age = 55;
var name = "Mike";
var isMarried = true;
var salary = 99999.50;
Console.WriteLine("AGE "+age.GetType());
Console.WriteLine("NAME " + name.GetType());
Console.WriteLine("MARRIED " + isMarried.GetType());
Console.WriteLine("SALARY " + salary.GetType());

            Console.ReadKey();
        }
    }
}

RESULT

AGE System.Int32
NAME System.String
MARRIED System.Boolean
SALARY System.Double

Factors Determining a Variables Behavior

The following factors determin a variable's behavior:

  1. Variable Scope: A scope defines the code that can access a given a variable. e.g If you declare a variable inside a loop, only code inside that loop can use that variable.
  2. Data Type: Determins the kind of data that a variable can hold, be it an integer,char, string, boolean etc.
  3. Variable Accessibility: This determines the code in other modules that can access the variable. For example if you declare a variable inside a a class at the class level and use the private modifier, only code in the class or its derived classescan use the variable. However if you declare the variable with the public keyowrd, code in other classes can also use the variable.
  4. Variable Lifetime: This determines how long the variable's value is valid. e.g A variable declared inside a method gets created when the method begins and destroyed when the method exits.

Variable Scope

A variable scope is the region of code within which a variable can be accessed. The scope of a given variable is influenced by the folllwoing scenarios:

  • A Field/Member Variable. This will be in scope as long as its containing class is in scope.
  • A Local Variable. This will be in scope until the end of the block statement normally confined within curly braces.
  • Local variables defined within loops or similar statement will be in scope until the end of that loop of statement.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *