Variables in C#

Variables in C# with Examples

In this article, I am going to discuss Variables in C# with Examples. Please read our previous article, where we discussed Operators in C# with Examples.

Understanding Variables in C# Language:

Why we are executing a program means to process the information or data. For example, a bank application. They are executing one program or one transaction. While executing the transaction, what they are actually doing is, they are processing the data like processing the account number, account name, balance, etc.

For every computer application, we must store the information at a particular location. Every computer has memory locations, and every memory location is identified by an address. Just consider in a classroom or in a movie hall, just consider the seating arrangement as memory locations.

Every memory location is identified by an address. For a better understanding, please have a look at the below image. As you can see in the below image, 128, 572, 1024, 5098, etc. are one-one memory addresses. We can treat all the addresses are positive integer values.

Understanding Variables in C# Language

What is the relation between variable and memory locations?

Suppose I want to store a value of 10 in the computer memory locations. Just consider a classroom, there is no restriction on the students where they can sit. That means the students will go and sit randomly at different locations. In the same way, the value 10 that we want to store in the computer memory locations will also go and be stored randomly at a particular memory location. For a better understanding, please have a look at the below image.

What is the relation between variable and memory locations?

How to access the data?

Now, I want to access the data i.e. value 10, and I just want to print that information. Then how can we print? How we can print the data means we will face the problems. The reason is, in which memory locations the data has been stored that we cannot identify because that data is stored randomly at a particular memory location. So, here accessing the memory location becomes very difficult after storing the information. So, what we should do before storing the information, we need to set the identity to the memory location where the data is going to be stored.

How we can set Identity to Memory Locations?

We can set the identity of the memory location by using variables or you can say identifiers. The following is the syntax to declare a variable by setting the identity of the memory location in the C# language. First, we need to write the data type followed by the identifier.

Syntax: data_type Identifier;

Example: int a; //Here integer is the data type and identifier can be any name and here we set it as a. So, whenever we declare a variable, it gets memory allocated. To one memory location, the identity is set as shown in the below image.

Variables in C# with Examples

Here “a” is a named memory location to the location 10344. Later when we can store an element into that memory location that is identified by the identifier “a” as follows.

a = 10; //Here, the value is 10 and we are setting this value into a memory location which is identified by “a” as shown in the below image.

Variables in C# with Examples

For example, in theatres, every seat is having some unique number and when you are coming you will sit in a particular seat that is allocated to you. Later if they want to access it, easily they can access it.

What is a Variable in C# Language?

A variable is a name given to a storage area that is used to store values of various data types. Each variable in C# needs to have a specific type, which determines the size and layout of the variable’s memory. For example, a variable can be of the type String, which means that it will be used to store a string value. Based on the data type, specific operations can be carried out on the variable. For instance, if we had an Integer variable, then operations such as addition and subtraction can be carried out on the variable. One can declare multiple variables in a program.

A name that is given for any computer memory location is called a variable. The purpose of the variable is to store some data. The user will access it by the variable name and the compiler will access it by the address. So, the C# variable is a named location in the computer memory where a program can manipulate the data. This location is used to hold the value of the variable. The value of the C# variable may get a change in the program. C# variable belonging to any of the data types like int, float, char, etc.

Note: In C# Language, variables are the data objects which are used to store a value. These values can be then manipulated during the execution of the program. You must declare the variable before using it in your program.

Rules for variable declaration in C#:
  1. A variable name must begin with a letter or underscore.
  2. Variables in C# are case sensitive
  3. They can be constructed with digits and letters.
  4. No special symbols are allowed other than underscores.
  5. sum, height, _value are some examples of the variable name
How to declare a variable in C#?

The Syntax for declaring a variable in C# is as follows:
Syntax: data_type variable_name;
Here, data_type is the type of data to be stored in the variable, and variable_name is the name given to that variable.
Example: int age;
Here, the data type is int and age is the name of the variable where the age variable can only hold an integer value.

How to initialize a variable in C#?

The Syntax for initializing a variable in C# as follows:
Syntax: data_type variable_name = value;
Here, data_type is the type of data to be stored in the variable, variable_name is the name given to the variable and value is the initial value stored in the variable.
Example: int age = 20;
Here, int is the data type and age is the name of the variable where 20 is the integer value stored inside the age variable.

Variables Scope and Lifetime in C#:

The scope of a variable in C# is the part of the program where the variable name can be referenced or can be used. You cannot refer to a variable before its declaration. Variable scope refers to the accessibility of a variable. The lifetime of a variable refers to the time in which a variable occupies a place in memory. The scope and lifetime of a variable are determined by how and where the variable is defined.

Scope defines the range of code where you can access a variable. We can divide the scope into two types:

  1. Method body scope variable is accessible in method body only (local variables, parameters)
  2. Class definition scope variable is accessible in the class definition (instance variables)

Lifetime defines as the amount of time a variable (or object) exists. We can divide lifetime into categories too:

  1. Method body lifetime exists on method body lifetime entry, disappears on method body exit (local variables, parameters).
  2. Class definition lifetime exists as long as the object is around (instance variables).
Types of Variables in C#:

Basically, there are five types of variables in C#. They are as follows:

  1. Local Variable
  2. Instance Variable
  3. Static Variable
  4. Const Variable
  5. Readonly Variable
Local Variables in C#:

The Local Variables in C# are declared inside the method of a class. The scope of the local variable is limited to the method, which means you cannot change the value of the local variable outside the method and you cannot even access it outside the method. The initialization of the local variable is mandatory.

  1. Scope of the Local Variables: Within the block in which it is declared.
  2. The lifetime of the Local Variable: Until the control leaves the block in which it is declared.
Example to Understand Local Variables in C#:

In the below example, the variable age is a Local Variable to the method EmployeeAge() and this variable can only be accessed within the EmployeeAge() method. You cannot access this variable outside the EmployeeAge() method.

using System;
namespace VariablesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.EmployeeAge();
            Console.ReadKey();
        }

        public void EmployeeAge()
        {
            //Local Variable age 
            int age = 30;
            Console.WriteLine("Employee age is: " + age);
        }
       
    }
}

Output: Employee age is: 30

Instance Variables in C#:

The instance variables in C# are also known as non-static variables. It is always declared in a class but outside the method, block, or constructor. The instance variable is created when an object of the class is created and destroyed when the object is destroyed. Instance Variables can only be accessed by creating the objects of the class. The initialization of the instance variable is not required, it takes the default value based on the data type of the variable.

  1. Scope of Instance Variable: Throughout the class except in static methods.
  2. The lifetime of Instance Variable: Until the object is available in the memory.
Example to Understand Instance Variables in C#:
using System;
namespace VariablesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Student obj = new Student();
            obj.Name = "Rohit";
            obj.Age = 30;
            Console.WriteLine($"Student Name: {obj.Name}, Age: {obj.Age}");
            Console.ReadKey();
        }
    }

    public class Student
    {
        // These variables are instance variables. 
        // These variables are in a class and are not inside any function 
        public string Name;
        public int Age;
    }
}

Output: Student Name: Rohit, Age: 30

Static Variables in C#:

The static variables in C# are also known as the Class Variable. The Static variables are created automatically at the start of the program execution and also destroyed automatically when program execution ends. These variables are declared similarly to instance variables, the difference is that static variables are declared using the static keyword within a class outside any method, constructor or block. Initialization of Static Variable is not mandatory, it takes the default value based on the variable data type. To access static variables, we need not create an object of that class, we can simply access the variable as class_name.variable_name;

  1. Scope of the Static Variable: Throughout the class.
  2. The Lifetime of Static Variable: Until the end of the program.
Example to Understand Static Variables in C#:
using System;
namespace VariablesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Student.Name = "Rohit";
            Student.Age = 30;
            Console.WriteLine($"Student Name: {Student.Name}, Age: {Student.Age}");
            Console.ReadKey();
        }
    }

    public class Student
    {
        // These variables are static variables. 
        public static string Name;
        public static int Age;
    }
}

Output: Student Name: Rohit, Age: 30

Difference between Instance variables and Static variables in C#
  1. In the case of Instance Variable, each object will have its own copy whereas We can only have one copy of a static variable irrespective of how many objects we create.
  2. In C#, the Changes made to the instance variable using one object will not be reflected in other objects as each object has its own copy of the instance variable. In the case of static variables, changes made in one object will be reflected in other objects as static variables are common to all objects of a class.
  3. We can access the instance variables through object references whereas the Static Variables can be accessed directly by using the class name in C#.
  4. In the life cycle of a class, a static variable is initialized only once, whereas instance variables are initialized for 0 times if no instance is created and n times if n number of instances are created.

The Syntax for static and instance variables in C#:
class Example
{
static int a; // static variable
int b; // instance variable
}

Constants Variables in C#

In C#, if we declare a variable by using the const keyword, then it is a constant variable and the value of the constant variable can’t be modified once after its declaration. So, it is mandatory to initialize at the time of declaration only.

Example to Understand Constants Variables in C#:

The following program will through an error because no value is provided at the time of constant variable declaration.

using System;
namespace VariablesDemo
{
    class Program
    {
        //Constant variable PI but no value is provided
        const double PI;
        static void Main(string[] args)
        {
            // creating object
            Program obj = new Program();

            // it will give an error
            Console.WriteLine("The value of PI is = " + Program.PI);
            Console.ReadKey();
        }
    }
}

Compile Time Error: A const field requires a value to be provided

Example showing the use of Constants Variables in C#:

The below program shows the use of constant variables.

using System;
namespace VariablesDemo
{
    class Program
    {
        //Constant variable
        const double PI = 3.14;
        static void Main(string[] args)
        {
            // creating object
            Program obj = new Program();
            Console.WriteLine("The value of PI is = " + Program.PI);
            Console.ReadKey();
        }
    }
}

Output: The value of PI is = 3.14

Note: The behavior of constant variables in C# 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. The difference between a static and constant variable is that the static variables can be modified whereas the constant variables in C# can’t be modified once it is declared.

Read-Only Variables in C#

When we declare a variable by using the readonly keyword, then it is known as a read-only variable and these variables can’t be modified like constants but after initialization. That means it is not mandatory to initialize a read-only variable at the time of its declaration, they can also be initialized under the constructor. That means we can modify the read-only variable value only within a constructor.

The behavior of read-only variables will be similar to the behavior of non-static variables in C#, i.e. initialized only after creating the instance of the class and once for each instance of the class created.

Example to Understand Read-Only Variables in C#:

In the following example, the read-only variable x is not initialized with any value but when we print the value of the variable the default value of int i.e. 0 will be displayed.

using System;
namespace VariablesDemo
{
    class Program
    {
        //Read-Only Variable
        readonly double x;
        static void Main(string[] args)
        {
            // creating object
            Program obj = new Program();
            Console.WriteLine("The value of x is = " + obj.x);
            Console.ReadKey();
        }
    }
}

Output: The value of x is = 0

Example To show the initialization of readonly variable in the constructor.
using System;
namespace VariablesDemo
{
    class Program
    {
        //Read-Only Variable
        readonly double x;

        //Constructor
        Program()
        {
            //Initializing Read-Only Variable x
            x = 50;
        }

        static void Main(string[] args)
        {
            // creating object
            Program obj = new Program();
            Console.WriteLine("The value of x is = " + obj.x);
            Console.ReadKey();
        }
    }
}

Output: The value of x is = 50

Note: The only difference between read-only and instance variables in C# is that the instance variables can be modified but the read-only variables can’t be modified. The Constant variable is a fixed value for the whole class whereas the read-only variable is a fixed value specific to an instance of the class.

In the next article, I am going to discuss Control Flow Statements in C# with Examples. Here, in this article, I try to explain Variables in C# with Examples and I hope you enjoy this Variables in C# article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.