Lession - 6 Variables in C#
Lession - 6 Variables in C#
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.
Whenever we are processing the data or information, the data or information must be at some
location. And we call that location as Memory Location and every computer has memory locations,
and every memory location is identified by an address. Just consider in a movie hall, the seating
arrangement as memory locations.
So, every memory location in the computer 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.
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.
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.
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. At the end of this
article, you will understand the different kinds of variables available in C# and their scope and life with
Examples.
For a better understanding, please have a look at the following example. In the below example, we
have declared three variables. The variable x is a static variable as it is declared using the static
modifier. The variable y is non-static by default and the variable z is static as it is declared inside a
static block. As the Main method is a static method and hence the variables declared inside the Main
method are also going to be static.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x; //Static Variable
int y; //Non-Static or Instance Variable
static void Main(string[] args)
{
int z; //Static Variable
}
}
}
Now, let us try to print the value of x and y inside the Main method. Let us initialize the x value to 100
and y value to 200. Here, you can print the value of x directly inside the Main method. But you cannot
print the value of y directly inside the Main method.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x = 100; //Static Variable
int y = 200; //Non-Static or Instance Variable
static void Main(string[] args)
{
Console.WriteLine($"x value: {x}");
Console.Read();
}
}
}
Output: x value: 100
Now, let us try to print the y value also directly. If we try to print the y value directly, then we will get a
compile time error saying an object reference is required for the non-static field, method, or
property 'Program.y'. For a better understanding, please have a look at the following example. Here,
we are trying to print the x and y value directly.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x = 100; //Static Variable
int y = 200; //Non-Static or Instance Variable
static void Main(string[] args)
{
Console.WriteLine($"x value: {x}");
Console.WriteLine($"x value: {y}");
Console.Read();
}
}
}
When you try to run the above code, you will get the following Compile Time Error.
This is because the memory for the variable y is going to be created only when we create an instance
of the class Program and for each instance. But x does not require an instance of the class. The
reason is a static variable is initialized immediately once the execution of the class starts.
So, until and unless we created the instance of the Program class, the memory will not be allocated
for the variable y and as long as the memory is not allocated for the variable y, we cannot access it.
So, once we create the instance of the Program class, the memory for variable y will be allocated and
then only we can access the variable y.
In the below example, we are creating an instance of the Program class and using that instance we
are accessing the y variable. But we are accessing directly the x variable.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x = 100; //Static Variable
int y = 200; //Non-Static or Instance Variable
static void Main(string[] args)
{
Console.WriteLine($"x value: {x}");
Program obj = new Program();
Console.WriteLine($"y value: {obj.y}");
Console.Read();
}
}
}
Now, when you run the above code, you will see that it will print both x and y value as shown in the
below image.
Note: The first point that you need to remember is while working with static and non-static variables,
static members of a class does not require the instance of a class for initialization and execution also,
whereas non-static members of a class require an instance of a class for both initialization and
execution.
The point we start the execution of a class to the point we end the execution of a class is called a Life
Cycle of a class. In the life cycle of a class, static variables are initialized one and only one time
whereas non-static or instance variables are initialized 0 time if no instance is created and n times if n
instances are created.
Let us understand this with an example. Please have a look at the below code. Here, we are creating
the Program class instance two times.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x = 100; //Static Variable
int y = 200; //Non-Static or Instance Variable
static void Main(string[] args)
{
Console.WriteLine($"x value: {x}");
Program obj1 = new Program();
Program obj2 = new Program();
Console.WriteLine($"obj1 y value: {obj1.y}");
Console.WriteLine($"obj2 y value: {obj2.y}");
Console.Read();
}
}
}
In the above example, as soon as the Program execution start, the memory is allocated for the static
variable y. Then we have created the instance of the Program class two times, that means the
memory is allocated for the y variable twice. Once for obj1 instance and once for obj2 instance. For a
better understanding, please have a look at the following diagram which represents the memory
architecture of the above example.
As you can see in the above image, the static variable x will be created only once and the non-static
variable y will be created two times as we are creating the instance of the Program class two time.
In the previous example, both the objects are having the same y value i.e. 100. Now, if you want then
you can provide different values to y variable using the constructor. Let us understand this with an
example. In the below example, we have created one constructor which takes one integer parameter
and this parameter value we are assigning to the non-static y variable. Further, while creating the
instance inside the Main method, we are passing different values. Now, whatever value we will pass,
that will be going to store inside the non-static y variable.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x = 100; //Static Variable
int y = 200; //Non-Static or Instance Variable
//Class Constructor
public Program(int a)
{
y = a;
}
Now, in the memory, the value of y for obj1 will be 300 and for obj2 it will be 400. But the x value is
going to be the same 100. For a better understanding, please have a look at the below image.
Now, you might have one question, can we initialize the static variable through constructor. The
answer is YES. We can initialize the static variable through constructor. But each time we initialize,
the static variable value will override with the new value. For a better understanding, please have a
look at the below example. In the below example, we are initializing the static variable through the
class constructor. As part of the constructor, we are initializing both x and y variable with the value of
a.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x = 100; //Static Variable
int y = 200; //Non-Static or Instance Variable
//Class Constructor
public Program(int a)
{
y = a; //Initializing non-static variable
x = a; //Initializing static variable
}
So, the point that you need to remember is if you are initializing the static variable through constructor,
then each time the constructor is executed, it will override the existing value of the static variable. So,
in general, we never initialize the static variables through constructor. If at all, you want to initialize the
variable through constructor, then make that variable as non-static.
Instance Variables in C#
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.
Static Variables in C#
1. Scope of the Static Variable: Throughout the class.
2. The Lifetime of Static Variable: Until the end of the program.
Suppose, you want to declare a constant PI in your program, then you can declare the constant as
follows:
const float PI = 3.14f;
If you not initializing the const variable at the time of its declaration, then you get a compiler error as
shown in the below image.
As you can you see it saying a const field requires a value to be provided which means while
declaring a constant it is mandatory to initialize the constant variable.
Note: The constant variables are going to be created one and only one time. This is because, we
cannot modify the constant values once after its declaration, then if it allows to create multiple copies
of the constant variable, then all those copies are going to store the same value which means it is
waste of memory. So, when we cannot modify a value, if we are creating the same copy multiple
times, then it is a waste of resource.
The behavior of constant variable is similar to the behavior of static variables i.e. initialized one and
only one time in the life cycle of class and does not require an instance of a class either for
initialization and execution. For a better understanding, please have a look at the following example.
The following code is self-explained, so please go through the comment lines.
using System;
namespace TypesOfVariables
{
internal class Program
{
const float PI = 3.14f; //Constant Variable
static int x = 100; //Static Variable
//We are going to initialize variable y through constructor
int y; //Non-Static or Instance Variable
//Constructor
public Program(int a)
{
//Initializing non-static variable
y = a;
}
The following diagram shows the memory representation of the above example.
Now, you might have one question, if both static and constant are behaving in the same way, then
what is the differences between them?
As you can see in the above image, it is clearly saying, the left-hand side of an assignment must
be a variable, property or indexer. But here, it is a constant and hence we are getting the
compilation error.
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 is
created. That means we can consider it as a non-static variable and to access readonly variables we
need an instance.
//Constructor
public Program(int a)
{
//Initializing non-static variable
y = a;
}
In the below example, we are initializing the readonly variable through the class constructor. Now, the
constructor taking two parameters. The first parameter will initialize the non-static variable and the
second parameter will initialize the readonly variable. So, while creating then instance, we need to
pass two integer values to the constructor function.
using System;
namespace TypesOfVariables
{
internal class Program
{
const float PI = 3.14f; //Constant Variable
static int x = 100; //Static Variable
//We are going to initialize variable y through constructor
int y; //Non-Static or Instance Variable
readonly int z; //Readonly Variable
//Constructor
public Program(int a, int b)
{
//Initializing non-static variable
y = a;
//Initializing Readonly variable
z = b;
}
For a better understanding of the above example, please have a look at the following diagram which
shows the memory representation.
Now, again you might have one question, if both non-static and readonly are behaving same, then
what is the differences between them?
//Constructor
public Program(int a, int b)
{
//Initializing non-static variable
y = a;
//Initializing Readonly variable
z = b;
}
Console.Read();
}
}
}
When you try to execute the above code, you will get the following Compilation Error.
As you can see in the above image, it is clearly saying that A readonly field cannot be assigned to
(except in a constructor or init-only setter of the type in which the field is defined or a variable
initializer). This means you can only initialize a readonly variable at the time of its declaration or
through a constructor. And here, we are trying the modify the readonly value inside the Main method
and hence we are getting the compilation error.