Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Value Type and Reference Type

In C#, these data types are categorized based on how they store their value in the memory. C# includes the following categories of data types:

  1. Value type
  2. Reference type
  3. Pointer type

Value Type

A data type is a value type if it holds a data value within its own memory space. It means the variables of these data types directly contain values.

tip

All the value types derive from System.ValueType, which in-turn, derives from System.Object. For example, consider integer variable int i = 100;

The system stores 100 in the memory space allocated for the variable i. The following image illustrates how 100 is stored at some hypothetical location in the memory (0x239110) for 'i':

Memory Allocation of Value Type Variable

The following data types are all of value type:

  • bool
  • byte
  • char
  • decimal
  • double
  • enum
  • float
  • int
  • long
  • sbyte
  • short
  • struct
  • uint
  • ulong
  • ushort

Passing Value Type Variables

When you pass a value-type variable from one method to another, the system creates a separate copy of a variable in another method. If value got changed in the one method, it wouldn't affect the variable in another method.

Example: Passing Value Type Variables
static void ChangeValue(int x)
{
    x =  200;

    Console.WriteLine(x);
}

static void Main(string[] args)
{
    int i = 100;

    Console.WriteLine(i);
    
    ChangeValue(i);
    
    Console.WriteLine(i);
}
Try it
Output:
100
200
100

In the above example, variable i in the Main() method remains unchanged even after we pass it to the ChangeValue() method and change it's value there.

Reference Type

Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored. In other words, a reference type contains a pointer to another memory location that holds the data.

For example, consider the following string variable:

string s = "Hello World!!";

The following image shows how the system allocates the memory for the above string variable.

Memory Allocation of Reference Type Variable

As you can see in the above image, the system selects a random location in memory (0x803200) for the variable s. The value of a variable s is 0x600000, which is the memory address of the actual data value. Thus, reference type stores the address of the location where the actual value is stored instead of the value itself.

The followings are reference type data types:

  • String
  • Arrays (even if their elements are value types)
  • Class
  • Delegate

Passing Reference Type Variables

When you pass a reference type variable from one method to another, it doesn't create a new copy; instead, it passes the variable's address. So, If we change the value of a variable in a method, it will also be reflected in the calling method.

Example: Passing Reference Type Variable
static void ChangeReferenceType(Student std2)
{
    std2.StudentName = "Steve";
}

static void Main(string[] args)
{
    Student std1 = new Student();
    std1.StudentName = "Bill";
    
    ChangeReferenceType(std1);

    Console.WriteLine(std1.StudentName);
}
Try it
Output:
Steve

In the above example, we pass the Student object std1 to the ChangeReferenceType() method. Here, it actually pass the memory address of std1. Thus, when the ChangeReferenceType() method changes StudentName, it is actually changing StudentName of std1 object, because std1 and std2 are both pointing to the same address in memory.

String is a reference type, but it is immutable. It means once we assigned a value, it cannot be changed. If we change a string value, then the compiler creates a new string object in the memory and point a variable to the new memory location. So, passing a string value to a function will create a new variable in the memory, and any change in the value in the function will not be reflected in the original value, as shown below.

Example: Passing String
static void ChangeReferenceType(string name)
{
    name = "Steve";
}

static void Main(string[] args)
{
    string name = "Bill";
    
    ChangeReferenceType(name);

    Console.WriteLine(name);
}
Try it
Output:
Bill

Null

The default value of a reference type variable is null when they are not initialized.Null means not refering to any object.

Null Reference Type

A value type variable cannot be null because it holds value, not a memory address. C# 2.0 introduced nullable types, using which you can assign null to a value type variable or declare a value type variable without assigning a value to it.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.