C# Types of Variables

C# Types of Variables

There are several types of variable, such as:

  1. Local Variables
  2. Instance Variables or Non – Static Variables
  3. Static Variables or Class Variables
  4. Constant Variables
  5. Read-only Variables

 

01. Local Variables

A local variable defined within a method or block or constructor. Once the variable is declared, those variables exist only within the block and we can access these variables only within the block. The variable is created when the function is called or the block is entered and it will be demolished once after existing from block or while the call returns from the function.

The scope of a local variable/constant is its own block and nested block.

You cannot declare another local variable with the same name in the block or in any nested blocks. For example:

static void Main()
{
       int x;
       {
         int y;
         int x;            // Error - x already defined
       }
       {
         int y;            // OK - y not in scope
       }
       Console.WriteLine (y);  // Error - y is out of scope
}
C# Example Program – Local Variables
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        public void GetAge()
        {
            int _age = 0;         // local variable
            _age = _age + 30;
            Console.WriteLine("The age is : " + _age);
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            Program _ageObj = new Program();
            _ageObj.GetAge();
        }
    }
}
Output:
C# Example Program – Local Variables

In the sample program, the variable “_age” is a local variable to the function GetAge(). The compiler will generate an error, once we apply the variable _age outside GetAge() function.

 

02. Instance Variables or Non – Static Variables

Instance variables are non-static variables and are declared in a class but outside any method, constructor or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers for instance variables.

C# Example Program – Instance Variables
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class ProgramMarks
    {
        // These variables are instance variables.
        // These variables are in a class and
        // are not inside any function
        int markEng;
        int markMath;
        int markPhysic;
       
        static void Main(string[] args)
        {
            // first object
            ProgramMarks obj1 = new ProgramMarks();
            obj1.markEng = 80;
            obj1.markMath = 70;
            obj1.markPhysic = 83;

            // second object
            ProgramMarks obj2 = new ProgramMarks();
            obj2.markEng = 90;
            obj2.markMath = 75;
            obj2.markPhysic = 97;

            // displaying marks for first object
            Console.WriteLine("Marks for first object:");
            Console.WriteLine(obj1.markEng);
            Console.WriteLine(obj1.markMath);
            Console.WriteLine(obj1.markPhysic);

            // displaying marks for second object
            Console.WriteLine("Marks for second object:");
            Console.WriteLine(obj2.markEng);
            Console.WriteLine(obj2.markMath);
            Console.WriteLine(obj2.markPhysic);
            Console.ReadLine();
        }
    }
}
Output:
C# Example Program – Instance Variables

In the program, the instance variables are markEng, markMath and markPhysic. We can create multiple objects each of the objects have its copy of the instance variable.

  • If there are multiple objects as in the above program, each object will have its own copies of instance variables.
  • It is clear from the above output that each object will have its own copy of the instance variable.

 

03. Static Variables or Class Variables

Static variables are also known as Class variables. If a variable is explicitly declared with the static modifier or if a variable is declared under any static block then these variables are known as static variables. 

A static variable is created at the beginning of the program execution and destroys at the end of the execution. For accessing static variables, we no need to create an object of the class; we can simply access the variable as:

Class_name.variable_name;

A static variable is declared using the keyword static within a class or outside any method or constructor.

  • Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
C# Example Program – Static Variable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class ProgramEmp
    {
        // static variable salary
        static double salary;
        static String name = "Adel";

        static void Main(string[] args)
        {
            // accessing static variable
            // without object
            ProgramEmp.salary = 5000;

            Console.WriteLine(ProgramEmp.name + "'s average salary:"
                                               + ProgramEmp.salary);
            Console.ReadLine();
        }
    }
}
Output:
C# Example Program – Static Variable

Note: Initialization of non-static variables is associated with instance creation and constructor calls, so non-static variables can be initialized through the constructor also. We don’t initialize a static variable through constructor because every time constructor call, it will override the existing value with a new value.

Difference between Instance variable & Static variable

 

  • Each object will have its own copy of instance variable whereas We can only have one copy of a static variable per class irrespective of how many objects we create.
  • Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of instance variable. In the case of static, changes will be reflected in other objects as static variables are common to all object of a class.
  • We can access instance variables through object references and Static Variables can be accessed directly using class name.
  • In the life cycle of a class a static variable ie initialized one and only one time, whereas instance variables are initialized for 0 times if no instance is created and n times if n instances are created.

The Syntax for static and instance variables are:

class Example
{
    static int a; // static variable
    int b;        // instance variable
 }

 

04. Constants Variables

If a variable is declared by using the keyword “const” then it as a constant variable and these constant variables can’t be modified once after their declaration, so it’s must initialize at the time of declaration only.

C# Example Program – Constant Variable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        int x = 15; // instance variable
        static int y = 30; // static variable
        const float max = 70; // constant variable
        
        static void Main(string[] args)
        {
            Program classObject = new Program(); // object creation
            Console.WriteLine("Value of x : " + classObject.x);
            Console.WriteLine("Value of y : " + Program.y);
            Console.WriteLine("Value of max " + Program.max);
            Console.ReadLine();
        }
    }
}
Output:
C# Example Program – Constant Variable
Important Points about Constant Variables:  

 

The behavior of constant variables will be similar to the behavior of static variables i.e. initialized one and only one time in the life cycle of a class and doesn’t require the instance of the class for accessing or initializing.

The difference between a static and constant variable is, static variables can be modified whereas constant variables can’t be modified once it declared.

 

05. Read-Only Variables

If a variable is declared by using the readonly keyword then it will be read-only variables and these variables can’t be modified like constants but after initialization.

C# Example Program – Read-Only
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        const float max = 70; // constant variable
        readonly int x; // read-only variable
        static void Main(string[] args)
        {
            Program classObject = new Program(); // object creation
            Console.WriteLine("Value of max: " + Program.max);
            Console.WriteLine("Value of x : " + classObject.x);
            Console.ReadLine();
        }
    }
}
Output:
C# Example Program – Read-Only
Important Points about Read-Only Variables:

 

The only difference between read-only and instance variables is that the instance variables can be modified but read-only variable can’t be modified.

Constant variable is a fixed value for the whole class whereas read-only variables is a fixed value specific to an instance of class.

 

Conclusion

Finally, you have known about how variables allow you to store data in different ways. 

In this article, we learned about how to declare and initialize variables and how to make use of it.