Overview Of Valuetype In C#

What Happened when we declare a variable in C#?

When we declare a variable in a C# application, it allocates some memory in the RAM. This memory has three things,

  • Name of the variable
  • Data type of the variable
  • Value of the variable.
    ex: Int i=10;

Here, in this example, i is the name of the variable; int is the Data type of the variable; and the value is 10.

We need a memory space (Location) to save this information. While allocating the space in C#, there are two types of memory allocation: stack memory and heap memory. 

Stack Memory

Value types are stored in Stack Memory. A Stack follows only one end of operations, i.e.,  Topend. In Stack, it will follow LIFO (Last In First Out) logic here, so the insertion and removal happen from one end only, i.e., Topend

 
Memory allocation and de-allocation are done using LIFO (Last In First Out) logic. 

Heap Memory: When we save something in Heap, it does not follow any approaches like FIFO or LIFO. It follows its own Random Approach.

 

Now, we will discuss the Value types and Reference types in C#.

By these two storage locations, we have 2 datatypes -

  1. Value Type
  2. Reference Type

Value types

Value type variables are stored in Stack Memory and thus called as Stack-based memory locations. The examples of Value types are - int, structs  and enums etc.

  • Structs and Enums are user-defined value types.
  • Value types are derived from System.ValueType which itself is derived from System.Object type.
  • Value type cannot inherit from other value type or reference type but can inherit from Interfaces.
  • Value types are sealed, i.e., no other type can inherit from them.
  • In value type data is stored Directly and we can call directly

Reference Type

Reference Type variables are stored in Heap Memory and thus, are known as Heap-based memory locations.

Example

string, object, class etc.

We can't call Reference type variables directly. Instead of that, we call it by its address, as shown below.

  1. Employee emp = new Employee(); 

Using this object reference, we call its name; that means it will be called by the address of a particular variable.

  1. emp.Name="Khadar";   

So, Reference types are called by address, not by value.

Next Recommended Reading Overview Of Collection In C#